On this page
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
unified_diff()returns a lazy generator of lines: Join with"".join(...)(if lines keep\nviasplitlines(keepends=True)) or"\n".join(...)withlineterm="".SequenceMatcheris O(n*m) worst-case: Avoid running it on huge multi-megabyte files; split by lines or cap input size first.autojunk=Trueby default: In sequences of 200+ items, elements appearing >1% of the time are treated as junk unless you passautojunk=False.
Common Functions
- difflib.context_diff() —
context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')— Compare two sequences of lines; generate the delta as a context diff. - difflib.diff_bytes() —
diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')— Compareaandb, two sequences of lines represented as bytes rather than str. This is a wrapper fordfunc, which is typically either unified_diff() or context_diff(). Inputs are losslessly converted to - difflib.get_close_matches() —
get_close_matches(word, possibilities, n=3, cutoff=0.6)— Use SequenceMatcher to return list of the best "good enough" matches. - difflib.ndiff() —
ndiff(a, b, linejunk=None, charjunk=<function IS_CHARACTER_JUNK at 0x109cd6140>)— Compareaandb(lists of strings); return aDiffer-style delta. - difflib.restore() —
restore(delta, which)— Generate one of the two sequences that generated a delta. - difflib.unified_diff() —
unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')— Compare two sequences of lines; generate the delta as a unified diff.
Classes & Objects
- difflib.Differ — Differ is a class for comparing sequences of lines of text, and producing human-readable differences or deltas. Differ uses SequenceMatcher both to compare sequences of lines, and to compare (Methods:
.compare()) - difflib.HtmlDiff — For producing HTML side by side comparison with change highlights. (Methods:
.make_file(),.make_table()) - difflib.Match — Match(a, b, size) (Methods:
.count(),.index()) - difflib.SequenceMatcher — SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm (Methods:
.find_longest_match(),.get_grouped_opcodes(),.get_matching_blocks(),.get_opcodes(),.quick_ratio(),.ratio())
Linked from
- tuts/python3
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/decimal
- tuts/python3/stdlib_module/difflib/context_diff
- tuts/python3/stdlib_module/difflib/diff_bytes
- tuts/python3/stdlib_module/difflib/Differ
- tuts/python3/stdlib_module/difflib/get_close_matches
- tuts/python3/stdlib_module/difflib/HtmlDiff
- tuts/python3/stdlib_module/difflib/Match
- tuts/python3/stdlib_module/difflib/ndiff
- tuts/python3/stdlib_module/difflib/restore
- tuts/python3/stdlib_module/difflib/SequenceMatcher
- tuts/python3/stdlib_module/difflib/unified_diff
- tuts/python3/stdlib_module/dis
- tuts/python3/stdlib_module/filecmp
- tuts/python3/stdlib_module/re
- tuts/python3/stdlib_module/readline
- tuts/python3/stdlib_module/rlcompleter
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/string
- tuts/python3/stdlib_module/stringprep
- tuts/python3/stdlib_module/textwrap
- tuts/python3/stdlib_module/unicodedata
Related notes
- tuts/python3/stdlib_module/decimal Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/context_diff Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/diff_bytes Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/Differ Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/get_close_matches Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/HtmlDiff Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/Match Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/ndiff Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/restore Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/difflib/SequenceMatcher Linked here; links to this page; shared tags: #stdlib