On this page
  1. difflib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Generating a Unified Patch Diff (unified_diff)
  7. 2. Inspecting Edit Operations (get_opcodes)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects

difflib

Prev: decimal | Up: stdlib_module | Next: dis
Rel: string, re, textwrap, unicodedata, stringprep
Ref: docs.python.org — difflib
Tags: #public #python3 #stdlib


Import

import difflib

Overview

Pure-Python sequence comparison helpers for generating unified/context text diffs (unified_diff), HTML side-by-side diffs (HtmlDiff), fuzzy string matching (get_close_matches), and similarity ratios (SequenceMatcher).

Quick Start

import difflib

matches = difflib.get_close_matches("pyhton", ["python", "cython", "rust", "perl"], n=2, cutoff=0.6)
assert matches == ["python", "cython"]

ratio = difflib.SequenceMatcher(None, "kitten", "sitting").ratio()
assert ratio > 0.6

Implementation Walkthrough

1. Generating a Unified Patch Diff (unified_diff)

import difflib

old = ["line 1\n", "line 2\n", "line 3\n"]
new = ["line 1\n", "line two\n", "line 3\n", "line 4\n"]

patch = "".join(difflib.unified_diff(old, new, fromfile="a.txt", tofile="b.txt", n=1))
assert "-line 2" in patch and "+line two" in patch and "+line 4" in patch

2. Inspecting Edit Operations (get_opcodes)

import difflib

sm = difflib.SequenceMatcher(None, "abcd", "abXd")
ops = [(tag, i1, i2, j1, j2) for tag, i1, i2, j1, j2 in sm.get_opcodes() if tag != "equal"]
assert ops == [("replace", 2, 3, 2, 3)]

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes