Debian Codegraph @

Doc/library/difflib.rst

raw
1 :mod:`!difflib` --- Helpers for computing deltas
2 ================================================
3
4 .. module:: difflib
5 :synopsis: Helpers for computing differences between objects.
6
7 .. moduleauthor:: Tim Peters <[email protected]>
8 .. sectionauthor:: Tim Peters <[email protected]>
9 .. Markup by Fred L. Drake, Jr. <[email protected]>
10
11 **Source code:** :source:`Lib/difflib.py`
12
13 .. testsetup::
14
15 import sys
16 from difflib import *
17
18 --------------
19
20 This module provides classes and functions for comparing sequences.
21 Most of them compare sequences of text lines (for example lists of strings,
22 or :term:`file objects <file object>`) and
23 produce :dfn:`diffs` -- reports on the differences.
24 Diffs can be produced in in various formats, including HTML and context
25 and unified diffs -- formats produced by tools like
26 :manpage:`diff <diff(1)>` and :manpage:`git diff <git-diff(1)>`.
27
28 Comparisons are done using a matching algorithm implemented in
29 :class:`SequenceMatcher` -- a flexible class for comparing pairs of sequences
30 of any type, not just text, so long as the sequence elements are
31 :term:`hashable`.
32
33
34 .. _difflib-junk:
35
36 Junk heuristic
37 --------------
38
39 :mod:`!difflib` uses a :dfn:`junk` heuristic: some items are deemed to be
40 :dfn:`junk`, and ignored when searching for similarities.
41 Ideally, these are uninteresting or common items, such as blank lines
42 or whitespace.
43
44 This heuristic can speed the algorithm up (because it reduces the number of
45 possible combinations) and it can produce results that are more understandable
46 for humans (typically breaking on whitespace).
47 But it can also cause pathological cases:
48
49 - Inappropriately chosen junk items can cause an unexpectedly **large** (but
50 still correct) result.
51 - The default heuristic is **asymmetric**: only the second sequence is
52 inspected when determining what is considered junk, so comparing A to B can
53 give different results than comparing B to A and reversing the result.
54
55 By default, if the second input sequence is at least 200 items long, items
56 that account for more than 1% it are considered *junk*.
57
58 Depending on your data, you should consider turning this heuristic off
59 (setting :class:`~difflib.SequenceMatcher`'s *autojunk* argument to to ``False``)
60 or tuning it (using the *isjunk* argument, perhaps to one of the
61 :ref:`predefined functions <difflib-isjunk-functions>`).
62
63
64 The :mod:`!difflib` algorithm
65 -----------------------------
66
67 The algorithm used in :class:`SequenceMatcher` predates, and is a little
68 fancier than, an algorithm published in the late 1980s by Ratcliff and
69 Obershelp under the hyperbolic name "gestalt pattern matching."
70 The idea is to find the longest contiguous subsequence common to both inputs,
71 then recursively handle the pieces of the sequences to the left and to the
72 right of the matching subsequence.
73
74 .. seealso::
75
76 `Pattern Matching: The Gestalt Approach <https://jacobfilipp.com/DrDobbs/articles/DDJ/1988/8807/8807c/8807c.htm>`_
77 Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
78 was published in Dr. Dobb's Journal in July, 1988.
79
80 As an extension to the Ratcliff and Obershelp algorithm, :mod:`!difflib`
81 searches for the longest *junk-free* contiguous subsequence.
82 See the :ref:`difflib-junk` section for details.
83
84 .. impl-detail:: Timing
85
86 The basic Ratcliff-Obershelp algorithm is cubic time in the worst
87 case and quadratic time in the expected case.
88 :mod:`difflib`'s algorithm is quadratic time for the worst case and has
89 expected-case behavior dependent in a complicated way on how many elements
90 the sequences have in common;
91 best case time is linear.
92
93
94 .. _difflib-diff-generation:
95
96 Diff generation
97 ---------------
98
99 .. _differ-objects:
100
101 .. class:: Differ
102
103 This is a class for comparing sequences of lines of text, and producing
104 human-readable differences or deltas. Differ uses :class:`SequenceMatcher`
105 both to compare sequences of lines, and to compare sequences of characters
106 within similar (near-matching) lines.
107
108 Each line of a :class:`Differ` delta begins with a two-letter code:
109
110 +----------+-------------------------------------------+
111 | Code | Meaning |
112 +==========+===========================================+
113 | ``'- '`` | line unique to sequence 1 |
114 +----------+-------------------------------------------+
115 | ``'+ '`` | line unique to sequence 2 |
116 +----------+-------------------------------------------+
117 | ``' '`` | line common to both sequences |
118 +----------+-------------------------------------------+
119 | ``'? '`` | line not present in either input sequence |
120 +----------+-------------------------------------------+
121
122 Lines beginning with '``?``' attempt to guide the eye to intraline differences,
123 and were not present in either input sequence. These lines can be confusing if
124 the sequences contain whitespace characters, such as spaces, tabs or line breaks.
125
126 Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
127 diffs. To the contrary, minimal diffs are often counter-intuitive for humans,
128 because they synch up anywhere possible, sometimes at accidental matches
129 100 pages apart.
130 Restricting synch points to contiguous matches preserves some notion of
131 locality, at the occasional cost of producing a longer diff.
132
133 The :class:`Differ` class has this constructor:
134
135 .. method:: __init__(linejunk=None, charjunk=None)
136
137 Optional keyword parameters *linejunk* and *charjunk* are for filter functions
138 (or ``None``):
139
140 *linejunk*: A function that accepts a single string argument, and returns true
141 if the string is junk. The default is ``None``, meaning that no line is
142 considered junk.
143
144 *charjunk*: A function that accepts a single character argument (a string of
145 length 1), and returns true if the character is junk. The default is ``None``,
146 meaning that no character is considered junk.
147
148 These junk-filtering functions speed up matching to find
149 differences and do not cause any differing lines or characters to
150 be ignored. Read the description of the
151 :meth:`~SequenceMatcher.find_longest_match` method's *isjunk*
152 parameter for an explanation.
153
154 :class:`Differ` objects are used (deltas generated) via a single method:
155
156
157 .. method:: Differ.compare(a, b)
158
159 Compare two sequences of lines, and generate the delta (a sequence of lines).
160
161 Each sequence must contain individual single-line strings ending with
162 newlines. Such sequences can be obtained from the
163 :meth:`~io.IOBase.readlines` method of file-like objects. The generated
164 delta also consists of newline-terminated strings, ready to be
165 printed as-is via the :meth:`~io.IOBase.writelines` method of a
166 file-like object.
167
168 .. class:: HtmlDiff
169
170 This class can be used to create an HTML table (or a complete HTML file
171 containing the table) showing a side by side, line by line comparison of text
172 with inter-line and intra-line change highlights. The table can be generated in
173 either full or contextual difference mode.
174
175 .. warning::
176
177 The trailing newlines get stripped before the diff, so the result can be
178 incomplete. See :gh:`71896` for details.
179
180 The constructor for this class is:
181
182
183 .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)
184
185 Initializes instance of :class:`HtmlDiff`.
186
187 *tabsize* is an optional keyword argument to specify tab stop spacing and
188 defaults to ``8``.
189
190 *wrapcolumn* is an optional keyword to specify column number where lines are
191 broken and wrapped, defaults to ``None`` where lines are not wrapped.
192
193 *linejunk* and *charjunk* are optional keyword arguments passed into :func:`ndiff`
194 (used by :class:`HtmlDiff` to generate the side by side HTML differences). See
195 :func:`ndiff` documentation for argument default values and descriptions.
196
197 The following methods are public:
198
199 .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, \
200 numlines=5, *, charset='utf-8')
201
202 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
203 is a complete HTML file containing a table showing line by line differences with
204 inter-line and intra-line changes highlighted.
205
206 *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
207 column header strings (both default to an empty string).
208
209 *context* and *numlines* are both optional keyword arguments. Set *context* to
210 ``True`` when contextual differences are to be shown, else the default is
211 ``False`` to show the full files. *numlines* defaults to ``5``. When *context*
212 is ``True`` *numlines* controls the number of context lines which surround the
213 difference highlights. When *context* is ``False`` *numlines* controls the
214 number of lines which are shown before a difference highlight when using the
215 "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
216 the next difference highlight at the top of the browser without any leading
217 context).
218
219 .. note::
220 *fromdesc* and *todesc* are interpreted as unescaped HTML and should be
221 properly escaped while receiving input from untrusted sources.
222
223 .. versionchanged:: 3.5
224 *charset* keyword-only argument was added. The default charset of
225 HTML document changed from ``'ISO-8859-1'`` to ``'utf-8'``.
226
227 .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)
228
229 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
230 is a complete HTML table showing line by line differences with inter-line and
231 intra-line changes highlighted.
232
233 The arguments for this method are the same as those for the :meth:`make_file`
234 method.
235
236
237
238 .. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
239
240 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
241 generating the delta lines) in context diff format.
242
243 Context diffs are a compact way of showing just the lines that have changed plus
244 a few lines of context. The changes are shown in a before/after style. The
245 number of context lines is set by *n* which defaults to three.
246
247 By default, the diff control lines (those with ``***`` or ``---``) are created
248 with a trailing newline. This is helpful so that inputs created from
249 :func:`io.IOBase.readlines` result in diffs that are suitable for use with
250 :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
251 newlines.
252
253 For inputs that do not have trailing newlines, set the *lineterm* argument to
254 ``""`` so that the output will be uniformly newline free.
255
256 The context diff format normally has a header for filenames and modification
257 times. Any or all of these may be specified using strings for *fromfile*,
258 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
259 expressed in the ISO 8601 format. If not specified, the
260 strings default to blanks.
261
262 >>> import sys
263 >>> from difflib import *
264 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
265 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
266 >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py',
267 ... tofile='after.py'))
268 *** before.py
269 --- after.py
270 ***************
271 *** 1,4 ****
272 ! bacon
273 ! eggs
274 ! ham
275 guido
276 --- 1,4 ----
277 ! python
278 ! eggy
279 ! hamster
280 guido
281
282 See :ref:`difflib-interface` for a more detailed example.
283
284
285 .. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6)
286
287 Return a list of the best "good enough" matches. *word* is a sequence for which
288 close matches are desired (typically a string), and *possibilities* is a list of
289 sequences against which to match *word* (typically a list of strings).
290
291 Optional argument *n* (default ``3``) is the maximum number of close matches to
292 return; *n* must be greater than ``0``.
293
294 Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
295 Possibilities that don't score at least that similar to *word* are ignored.
296
297 The best (no more than *n*) matches among the possibilities are returned in a
298 list, sorted by similarity score, most similar first.
299
300 >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
301 ['apple', 'ape']
302 >>> import keyword
303 >>> get_close_matches('wheel', keyword.kwlist)
304 ['while']
305 >>> get_close_matches('pineapple', keyword.kwlist)
306 []
307 >>> get_close_matches('accept', keyword.kwlist)
308 ['except']
309
310
311 .. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)
312
313 Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
314 delta (a :term:`generator` generating the delta lines).
315
316 Optional keyword parameters *linejunk* and *charjunk* are filtering functions
317 (or ``None``):
318
319 *linejunk*: A function that accepts a single string argument, and returns
320 true if the string is junk, or false if not. The default is ``None``. There
321 is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines
322 without visible characters, except for at most one hash character (``'#'``)
323 -- however the underlying :class:`SequenceMatcher` class does a dynamic
324 analysis of which lines are so frequent as to constitute noise, and this
325 usually works better than using this function.
326
327 *charjunk*: A function that accepts a character (a string of length 1), and
328 returns if the character is junk, or false if not. The default is module-level
329 function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
330 blank or tab; it's a bad idea to include newline in this!).
331
332 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
333 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
334 >>> print(''.join(diff), end="")
335 - one
336 ? ^
337 + ore
338 ? ^
339 - two
340 - three
341 ? -
342 + tree
343 + emu
344
345
346 .. function:: restore(sequence, which)
347
348 Return one of the two sequences that generated a delta.
349
350 Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
351 lines originating from file 1 or 2 (parameter *which*), stripping off line
352 prefixes.
353
354 Example:
355
356 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
357 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
358 >>> diff = list(diff) # materialize the generated delta into a list
359 >>> print(''.join(restore(diff, 1)), end="")
360 one
361 two
362 three
363 >>> print(''.join(restore(diff, 2)), end="")
364 ore
365 tree
366 emu
367
368
369 .. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
370
371 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
372 generating the delta lines) in unified diff format.
373
374 Unified diffs are a compact way of showing just the lines that have changed plus
375 a few lines of context. The changes are shown in an inline style (instead of
376 separate before/after blocks). The number of context lines is set by *n* which
377 defaults to three.
378
379 By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
380 created with a trailing newline. This is helpful so that inputs created from
381 :func:`io.IOBase.readlines` result in diffs that are suitable for use with
382 :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
383 newlines.
384
385 For inputs that do not have trailing newlines, set the *lineterm* argument to
386 ``""`` so that the output will be uniformly newline free.
387
388 The unified diff format normally has a header for filenames and modification
389 times. Any or all of these may be specified using strings for *fromfile*,
390 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
391 expressed in the ISO 8601 format. If not specified, the
392 strings default to blanks.
393
394 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
395 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
396 >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
397 --- before.py
398 +++ after.py
399 @@ -1,4 +1,4 @@
400 -bacon
401 -eggs
402 -ham
403 +python
404 +eggy
405 +hamster
406 guido
407
408 See :ref:`difflib-interface` for a more detailed example.
409
410 .. function:: diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\n')
411
412 Compare *a* and *b* (lists of bytes objects) using *dfunc*; yield a
413 sequence of delta lines (also bytes) in the format returned by *dfunc*.
414 *dfunc* must be a callable, typically either :func:`unified_diff` or
415 :func:`context_diff`.
416
417 Allows you to compare data with unknown or inconsistent encoding. All
418 inputs except *n* must be bytes objects, not str. Works by losslessly
419 converting all inputs (except *n*) to str, and calling ``dfunc(a, b,
420 fromfile, tofile, fromfiledate, tofiledate, n, lineterm)``. The output of
421 *dfunc* is then converted back to bytes, so the delta lines that you
422 receive have the same unknown/inconsistent encodings as *a* and *b*.
423
424 .. versionadded:: 3.5
425
426
427 .. _difflib-isjunk-functions:
428
429 Junk definition functions
430 -------------------------
431
432 .. function:: IS_LINE_JUNK(line)
433
434 Return ``True`` for ignorable lines. The line *line* is ignorable if *line* is
435 blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a
436 default for parameter *linejunk* in :func:`ndiff` in older versions.
437
438
439 .. function:: IS_CHARACTER_JUNK(ch)
440
441 Return ``True`` for ignorable characters. The character *ch* is ignorable if *ch*
442 is a space or tab, otherwise it is not ignorable. Used as a default for
443 parameter *charjunk* in :func:`ndiff`.
444
445
446 .. _sequence-matcher:
447
448 SequenceMatcher objects
449 -----------------------
450
451 .. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
452
453 Optional argument *isjunk* must be ``None`` (the default) or a one-argument
454 function that takes a sequence element and returns true if and only if the
455 element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
456 equivalent to passing ``lambda x: False``; in other words, no elements are ignored.
457 For example, pass::
458
459 lambda x: x in " \t"
460
461 if you're comparing lines as sequences of characters, and don't want to synch up
462 on blanks or hard tabs.
463
464 The optional arguments *a* and *b* are sequences to be compared; both default to
465 empty strings. The elements of both sequences must be :term:`hashable`.
466
467 The optional argument *autojunk* can be used to disable the automatic junk
468 heuristic.
469
470 .. versionchanged:: 3.2
471 Added the *autojunk* parameter.
472
473 SequenceMatcher objects get three data attributes: *bjunk* is the
474 set of elements of *b* for which *isjunk* is ``True``; *bpopular* is the set of
475 non-junk elements considered popular by the heuristic (if it is not
476 disabled); *b2j* is a dict mapping the remaining elements of *b* to a list
477 of positions where they occur. All three are reset whenever *b* is reset
478 with :meth:`set_seqs` or :meth:`set_seq2`.
479
480 .. versionadded:: 3.2
481 The *bjunk* and *bpopular* attributes.
482
483 :class:`SequenceMatcher` objects have the following methods:
484
485 .. method:: set_seqs(a, b)
486
487 Set the two sequences to be compared.
488
489 :class:`SequenceMatcher` computes and caches detailed information about the
490 second sequence, so if you want to compare one sequence against many
491 sequences, use :meth:`set_seq2` to set the commonly used sequence once and
492 call :meth:`set_seq1` repeatedly, once for each of the other sequences.
493
494
495 .. method:: set_seq1(a)
496
497 Set the first sequence to be compared. The second sequence to be compared
498 is not changed.
499
500
501 .. method:: set_seq2(b)
502
503 Set the second sequence to be compared. The first sequence to be compared
504 is not changed.
505
506
507 .. method:: find_longest_match(alo=0, ahi=None, blo=0, bhi=None)
508
509 Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
510
511 If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
512 ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
513 <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
514 k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
515 <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
516 all maximal matching blocks, return one that starts earliest in *a*, and
517 of all those maximal matching blocks that start earliest in *a*, return
518 the one that starts earliest in *b*.
519
520 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
521 >>> s.find_longest_match(0, 5, 0, 9)
522 Match(a=0, b=4, size=5)
523
524 If *isjunk* was provided, first the longest matching block is determined
525 as above, but with the additional restriction that no junk element appears
526 in the block. Then that block is extended as far as possible by matching
527 (only) junk elements on both sides. So the resulting block never matches
528 on junk except as identical junk happens to be adjacent to an interesting
529 match.
530
531 Here's the same example as before, but considering blanks to be junk. That
532 prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
533 second sequence directly. Instead only the ``'abcd'`` can match, and
534 matches the leftmost ``'abcd'`` in the second sequence:
535
536 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
537 >>> s.find_longest_match(0, 5, 0, 9)
538 Match(a=1, b=0, size=4)
539
540 If no blocks match, this returns ``(alo, blo, 0)``.
541
542 This method returns a :term:`named tuple` ``Match(a, b, size)``.
543
544 .. versionchanged:: 3.9
545 Added default arguments.
546
547
548 .. method:: get_matching_blocks()
549
550 Return list of triples describing non-overlapping matching subsequences.
551 Each triple is of the form ``(i, j, n)``,
552 and means that ``a[i:i+n] == b[j:j+n]``. The
553 triples are monotonically increasing in *i* and *j*.
554
555 The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
556 is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
557 are adjacent triples in the list, and the second is not the last triple in
558 the list, then ``i+n < i'`` or ``j+n < j'``; in other words, adjacent
559 triples always describe non-adjacent equal blocks.
560
561 .. XXX Explain why a dummy is used!
562
563 .. doctest::
564
565 >>> s = SequenceMatcher(None, "abxcd", "abcd")
566 >>> s.get_matching_blocks()
567 [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
568
569
570 .. method:: get_opcodes()
571
572 Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
573 of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
574 0``, and remaining tuples have *i1* equal to the *i2* from the preceding
575 tuple, and, likewise, *j1* equal to the previous *j2*.
576
577 The *tag* values are strings, with these meanings:
578
579 +---------------+---------------------------------------------+
580 | Value | Meaning |
581 +===============+=============================================+
582 | ``'replace'`` | ``a[i1:i2]`` should be replaced by |
583 | | ``b[j1:j2]``. |
584 +---------------+---------------------------------------------+
585 | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
586 | | ``j1 == j2`` in this case. |
587 +---------------+---------------------------------------------+
588 | ``'insert'`` | ``b[j1:j2]`` should be inserted at |
589 | | ``a[i1:i1]``. Note that ``i1 == i2`` in |
590 | | this case. |
591 +---------------+---------------------------------------------+
592 | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
593 | | are equal). |
594 +---------------+---------------------------------------------+
595
596 For example::
597
598 >>> a = "qabxcd"
599 >>> b = "abycdf"
600 >>> s = SequenceMatcher(None, a, b)
601 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
602 ... print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
603 ... tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
604 delete a[0:1] --> b[0:0] 'q' --> ''
605 equal a[1:3] --> b[0:2] 'ab' --> 'ab'
606 replace a[3:4] --> b[2:3] 'x' --> 'y'
607 equal a[4:6] --> b[3:5] 'cd' --> 'cd'
608 insert a[6:6] --> b[5:6] '' --> 'f'
609
610
611 .. method:: get_grouped_opcodes(n=3)
612
613 Return a :term:`generator` of groups with up to *n* lines of context.
614
615 Starting with the groups returned by :meth:`get_opcodes`, this method
616 splits out smaller change clusters and eliminates intervening ranges which
617 have no changes.
618
619 The groups are returned in the same format as :meth:`get_opcodes`.
620
621
622 .. method:: ratio()
623
624 Return a measure of the sequences' similarity as a float in the range [0,
625 1].
626
627 Where T is the total number of elements in both sequences, and M is the
628 number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
629 sequences are identical, and ``0.0`` if they have nothing in common.
630
631 This is expensive to compute if :meth:`get_matching_blocks` or
632 :meth:`get_opcodes` hasn't already been called, in which case you may want
633 to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
634 upper bound.
635
636
637 .. method:: quick_ratio()
638
639 Return an upper bound on :meth:`ratio` relatively quickly.
640
641
642 .. method:: real_quick_ratio()
643
644 Return an upper bound on :meth:`ratio` very quickly.
645
646
647 The three methods that return the ratio of matching to total characters can give
648 different results due to differing levels of approximation, although
649 :meth:`~SequenceMatcher.quick_ratio` and :meth:`~SequenceMatcher.real_quick_ratio`
650 are always at least as large as :meth:`~SequenceMatcher.ratio`:
651
652 >>> s = SequenceMatcher(None, "abcd", "bcde")
653 >>> s.ratio()
654 0.75
655 >>> s.quick_ratio()
656 0.75
657 >>> s.real_quick_ratio()
658 1.0
659
660
661 Examples
662 --------
663
664 .. _sequencematcher-examples:
665
666 SequenceMatcher examples
667 ........................
668
669 This example compares two strings, considering blanks to be "junk":
670
671 >>> s = SequenceMatcher(lambda x: x == " ",
672 ... "private Thread currentThread;",
673 ... "private volatile Thread currentThread;")
674
675 :meth:`~SequenceMatcher.ratio` returns a float in [0, 1], measuring the similarity of the
676 sequences. As a rule of thumb, a :meth:`~SequenceMatcher.ratio` value over 0.6 means the
677 sequences are close matches:
678
679 >>> print(round(s.ratio(), 3))
680 0.866
681
682 If you're only interested in where the sequences match,
683 :meth:`~SequenceMatcher.get_matching_blocks` is handy:
684
685 >>> for block in s.get_matching_blocks():
686 ... print("a[%d] and b[%d] match for %d elements" % block)
687 a[0] and b[0] match for 8 elements
688 a[8] and b[17] match for 21 elements
689 a[29] and b[38] match for 0 elements
690
691 Note that the last tuple returned by :meth:`~SequenceMatcher.get_matching_blocks`
692 is always a dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
693 tuple element (number of elements matched) is ``0``.
694
695 If you want to know how to change the first sequence into the second, use
696 :meth:`~SequenceMatcher.get_opcodes`:
697
698 >>> for opcode in s.get_opcodes():
699 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
700 equal a[0:8] b[0:8]
701 insert a[8:8] b[8:17]
702 equal a[8:29] b[17:38]
703
704 .. seealso::
705
706 * The :func:`get_close_matches` function in this module which shows how
707 simple code building on :class:`SequenceMatcher` can be used to do useful
708 work.
709
710 * `Simple version control recipe
711 <https://code.activestate.com/recipes/576729-simple-version-control/>`_ for a small application
712 built with :class:`SequenceMatcher`.
713
714
715 .. _differ-examples:
716
717 Differ example
718 ..............
719
720 This example compares two texts. First we set up the texts, sequences of
721 individual single-line strings ending with newlines (such sequences can also be
722 obtained from the :meth:`~io.IOBase.readlines` method of file-like objects):
723
724 >>> text1 = ''' 1. Beautiful is better than ugly.
725 ... 2. Explicit is better than implicit.
726 ... 3. Simple is better than complex.
727 ... 4. Complex is better than complicated.
728 ... '''.splitlines(keepends=True)
729 >>> len(text1)
730 4
731 >>> text1[0][-1]
732 '\n'
733 >>> text2 = ''' 1. Beautiful is better than ugly.
734 ... 3. Simple is better than complex.
735 ... 4. Complicated is better than complex.
736 ... 5. Flat is better than nested.
737 ... '''.splitlines(keepends=True)
738
739 Next we instantiate a Differ object:
740
741 >>> d = Differ()
742
743 Note that when instantiating a :class:`Differ` object we may pass functions to
744 filter out line and character "junk." See the :meth:`Differ` constructor for
745 details.
746
747 Finally, we compare the two:
748
749 >>> result = list(d.compare(text1, text2))
750
751 ``result`` is a list of strings, so let's pretty-print it:
752
753 >>> from pprint import pprint
754 >>> pprint(result)
755 [' 1. Beautiful is better than ugly.\n',
756 '- 2. Explicit is better than implicit.\n',
757 '- 3. Simple is better than complex.\n',
758 '+ 3. Simple is better than complex.\n',
759 '? ++\n',
760 '- 4. Complex is better than complicated.\n',
761 '? ^ ---- ^\n',
762 '+ 4. Complicated is better than complex.\n',
763 '? ++++ ^ ^\n',
764 '+ 5. Flat is better than nested.\n']
765
766 As a single multi-line string it looks like this:
767
768 >>> import sys
769 >>> sys.stdout.writelines(result)
770 1. Beautiful is better than ugly.
771 - 2. Explicit is better than implicit.
772 - 3. Simple is better than complex.
773 + 3. Simple is better than complex.
774 ? ++
775 - 4. Complex is better than complicated.
776 ? ^ ---- ^
777 + 4. Complicated is better than complex.
778 ? ++++ ^ ^
779 + 5. Flat is better than nested.
780
781
782 .. _difflib-interface:
783
784 A command-line interface to difflib
785 ...................................
786
787 This example shows how to use difflib to create a ``diff``-like utility.
788
789 .. literalinclude:: ../includes/diff.py
790
791 ndiff example
792 .............
793
794 This example shows how to use :func:`difflib.ndiff`.
795
796 .. literalinclude:: ../includes/ndiff.py