difflib.rst 29.2 KB
Newer Older
1 2 3 4 5
:mod:`difflib` --- Helpers for computing deltas
===============================================

.. module:: difflib
   :synopsis: Helpers for computing differences between objects.
6

7 8
.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
9
.. Markup by Fred L. Drake, Jr. <fdrake@acm.org>
10

11 12
**Source code:** :source:`Lib/difflib.py`

Christian Heimes's avatar
Christian Heimes committed
13
.. testsetup::
14

Christian Heimes's avatar
Christian Heimes committed
15 16
   import sys
   from difflib import *
17

18 19
--------------

20 21 22 23 24
This module provides classes and functions for comparing sequences. It
can be used for example, for comparing files, and can produce difference
information in various formats, including HTML and context and unified
diffs. For comparing directories and files, see also, the :mod:`filecmp` module.

25

26 27 28
.. class:: SequenceMatcher

   This is a flexible class for comparing pairs of sequences of any type, so long
29
   as the sequence elements are :term:`hashable`.  The basic algorithm predates, and is a
30 31 32
   little fancier than, an algorithm published in the late 1980's by Ratcliff and
   Obershelp under the hyperbolic name "gestalt pattern matching."  The idea is to
   find the longest contiguous matching subsequence that contains no "junk"
33 34 35
   elements; these "junk" elements are ones that are uninteresting in some
   sense, such as blank lines or whitespace.  (Handling junk is an
   extension to the Ratcliff and Obershelp algorithm.) The same
36 37 38 39 40 41 42 43 44 45
   idea is then applied recursively to the pieces of the sequences to the left and
   to the right of the matching subsequence.  This does not yield minimal edit
   sequences, but does tend to yield matches that "look right" to people.

   **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst
   case and quadratic time in the expected case. :class:`SequenceMatcher` is
   quadratic time for the worst case and has expected-case behavior dependent in a
   complicated way on how many elements the sequences have in common; best case
   time is linear.

46 47 48 49 50 51 52 53
   **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that
   automatically treats certain sequence items as junk. The heuristic counts how many
   times each individual item appears in the sequence. If an item's duplicates (after
   the first one) account for more than 1% of the sequence and the sequence is at least
   200 items long, this item is marked as "popular" and is treated as junk for
   the purpose of sequence matching. This heuristic can be turned off by setting
   the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`.

54 55 56
   .. versionadded:: 3.2
      The *autojunk* parameter.

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

.. class:: Differ

   This is a class for comparing sequences of lines of text, and producing
   human-readable differences or deltas.  Differ uses :class:`SequenceMatcher`
   both to compare sequences of lines, and to compare sequences of characters
   within similar (near-matching) lines.

   Each line of a :class:`Differ` delta begins with a two-letter code:

   +----------+-------------------------------------------+
   | Code     | Meaning                                   |
   +==========+===========================================+
   | ``'- '`` | line unique to sequence 1                 |
   +----------+-------------------------------------------+
   | ``'+ '`` | line unique to sequence 2                 |
   +----------+-------------------------------------------+
   | ``'  '`` | line common to both sequences             |
   +----------+-------------------------------------------+
   | ``'? '`` | line not present in either input sequence |
   +----------+-------------------------------------------+

   Lines beginning with '``?``' attempt to guide the eye to intraline differences,
   and were not present in either input sequence. These lines can be confusing if
   the sequences contain tab characters.


.. class:: HtmlDiff

   This class can be used to create an HTML table (or a complete HTML file
   containing the table) showing a side by side, line by line comparison of text
   with inter-line and intra-line change highlights.  The table can be generated in
   either full or contextual difference mode.

   The constructor for this class is:


94
   .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)
95 96 97 98 99 100 101 102 103

      Initializes instance of :class:`HtmlDiff`.

      *tabsize* is an optional keyword argument to specify tab stop spacing and
      defaults to ``8``.

      *wrapcolumn* is an optional keyword to specify column number where lines are
      broken and wrapped, defaults to ``None`` where lines are not wrapped.

104
      *linejunk* and *charjunk* are optional keyword arguments passed into :func:`ndiff`
105
      (used by :class:`HtmlDiff` to generate the side by side HTML differences).  See
106
      :func:`ndiff` documentation for argument default values and descriptions.
107 108 109

   The following methods are public:

110 111
   .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, \
                         numlines=5, *, charset='utf-8')
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

      Compares *fromlines* and *tolines* (lists of strings) and returns a string which
      is a complete HTML file containing a table showing line by line differences with
      inter-line and intra-line changes highlighted.

      *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
      column header strings (both default to an empty string).

      *context* and *numlines* are both optional keyword arguments. Set *context* to
      ``True`` when contextual differences are to be shown, else the default is
      ``False`` to show the full files. *numlines* defaults to ``5``.  When *context*
      is ``True`` *numlines* controls the number of context lines which surround the
      difference highlights.  When *context* is ``False`` *numlines* controls the
      number of lines which are shown before a difference highlight when using the
      "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
      the next difference highlight at the top of the browser without any leading
      context).

130 131 132 133
      .. versionchanged:: 3.5
         *charset* keyword-only argument was added.  The default charset of
         HTML document changed from ``'ISO-8859-1'`` to ``'utf-8'``.

134
   .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)
135 136 137 138 139 140 141 142 143 144 145 146

      Compares *fromlines* and *tolines* (lists of strings) and returns a string which
      is a complete HTML table showing line by line differences with inter-line and
      intra-line changes highlighted.

      The arguments for this method are the same as those for the :meth:`make_file`
      method.

   :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
   contains a good example of its use.


147
.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
148

149 150
   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
   generating the delta lines) in context diff format.
151 152 153 154 155 156 157

   Context diffs are a compact way of showing just the lines that have changed plus
   a few lines of context.  The changes are shown in a before/after style.  The
   number of context lines is set by *n* which defaults to three.

   By default, the diff control lines (those with ``***`` or ``---``) are created
   with a trailing newline.  This is helpful so that inputs created from
158 159
   :func:`io.IOBase.readlines` result in diffs that are suitable for use with
   :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
160 161 162 163 164 165 166
   newlines.

   For inputs that do not have trailing newlines, set the *lineterm* argument to
   ``""`` so that the output will be uniformly newline free.

   The context diff format normally has a header for filenames and modification
   times.  Any or all of these may be specified using strings for *fromfile*,
167 168
   *tofile*, *fromfiledate*, and *tofiledate*.  The modification times are normally
   expressed in the ISO 8601 format. If not specified, the
169 170
   strings default to blanks.

Christian Heimes's avatar
Christian Heimes committed
171 172
      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
173
      >>> sys.stdout.writelines(context_diff(s1, s2, fromfile='before.py', tofile='after.py'))
Christian Heimes's avatar
Christian Heimes committed
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
      *** before.py
      --- after.py
      ***************
      *** 1,4 ****
      ! bacon
      ! eggs
      ! ham
        guido
      --- 1,4 ----
      ! python
      ! eggy
      ! hamster
        guido

   See :ref:`difflib-interface` for a more detailed example.
189 190


191
.. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6)
192 193 194 195 196 197 198 199 200 201 202 203

   Return a list of the best "good enough" matches.  *word* is a sequence for which
   close matches are desired (typically a string), and *possibilities* is a list of
   sequences against which to match *word* (typically a list of strings).

   Optional argument *n* (default ``3``) is the maximum number of close matches to
   return; *n* must be greater than ``0``.

   Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
   Possibilities that don't score at least that similar to *word* are ignored.

   The best (no more than *n*) matches among the possibilities are returned in a
Christian Heimes's avatar
Christian Heimes committed
204
   list, sorted by similarity score, most similar first.
205 206 207 208 209 210

      >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
      ['apple', 'ape']
      >>> import keyword
      >>> get_close_matches('wheel', keyword.kwlist)
      ['while']
211
      >>> get_close_matches('pineapple', keyword.kwlist)
212 213 214 215 216
      []
      >>> get_close_matches('accept', keyword.kwlist)
      ['except']


217
.. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)
218

219 220
   Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
   delta (a :term:`generator` generating the delta lines).
221

222
   Optional keyword parameters *linejunk* and *charjunk* are filtering functions
223 224
   (or ``None``):

225 226 227 228 229 230 231
   *linejunk*: A function that accepts a single string argument, and returns
   true if the string is junk, or false if not. The default is ``None``. There
   is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines
   without visible characters, except for at most one pound character (``'#'``)
   -- however the underlying :class:`SequenceMatcher` class does a dynamic
   analysis of which lines are so frequent as to constitute noise, and this
   usually works better than using this function.
232 233 234 235

   *charjunk*: A function that accepts a character (a string of length 1), and
   returns if the character is junk, or false if not. The default is module-level
   function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
236
   blank or tab; it's a bad idea to include newline in this!).
237

Christian Heimes's avatar
Christian Heimes committed
238
   :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
239

240 241
      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
      ...              'ore\ntree\nemu\n'.splitlines(keepends=True))
242
      >>> print(''.join(diff), end="")
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
      - one
      ?  ^
      + ore
      ?  ^
      - two
      - three
      ?  -
      + tree
      + emu


.. function:: restore(sequence, which)

   Return one of the two sequences that generated a delta.

   Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
   lines originating from file 1 or 2 (parameter *which*), stripping off line
   prefixes.

Christian Heimes's avatar
Christian Heimes committed
262
   Example:
263

264 265
      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
      ...              'ore\ntree\nemu\n'.splitlines(keepends=True))
266
      >>> diff = list(diff) # materialize the generated delta into a list
267
      >>> print(''.join(restore(diff, 1)), end="")
268 269 270
      one
      two
      three
271
      >>> print(''.join(restore(diff, 2)), end="")
272 273 274 275 276
      ore
      tree
      emu


277
.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
278

279 280
   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
   generating the delta lines) in unified diff format.
281 282

   Unified diffs are a compact way of showing just the lines that have changed plus
283
   a few lines of context.  The changes are shown in an inline style (instead of
284 285 286 287 288
   separate before/after blocks).  The number of context lines is set by *n* which
   defaults to three.

   By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
   created with a trailing newline.  This is helpful so that inputs created from
289 290
   :func:`io.IOBase.readlines` result in diffs that are suitable for use with
   :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
291 292 293 294 295 296 297
   newlines.

   For inputs that do not have trailing newlines, set the *lineterm* argument to
   ``""`` so that the output will be uniformly newline free.

   The context diff format normally has a header for filenames and modification
   times.  Any or all of these may be specified using strings for *fromfile*,
298 299
   *tofile*, *fromfiledate*, and *tofiledate*.  The modification times are normally
   expressed in the ISO 8601 format. If not specified, the
300 301
   strings default to blanks.

Christian Heimes's avatar
Christian Heimes committed
302 303 304

      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
305
      >>> sys.stdout.writelines(unified_diff(s1, s2, fromfile='before.py', tofile='after.py'))
Christian Heimes's avatar
Christian Heimes committed
306 307 308 309 310 311 312 313 314 315 316 317
      --- before.py
      +++ after.py
      @@ -1,4 +1,4 @@
      -bacon
      -eggs
      -ham
      +python
      +eggy
      +hamster
       guido

   See :ref:`difflib-interface` for a more detailed example.
318

319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
.. function:: diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'', fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\\n')

   Compare *a* and *b* (lists of bytes objects) using *dfunc*; yield a
   sequence of delta lines (also bytes) in the format returned by *dfunc*.
   *dfunc* must be a callable, typically either :func:`unified_diff` or
   :func:`context_diff`.

   Allows you to compare data with unknown or inconsistent encoding. All
   inputs except *n* must be bytes objects, not str. Works by losslessly
   converting all inputs (except *n*) to str, and calling ``dfunc(a, b,
   fromfile, tofile, fromfiledate, tofiledate, n, lineterm)``. The output of
   *dfunc* is then converted back to bytes, so the delta lines that you
   receive have the same unknown/inconsistent encodings as *a* and *b*.

   .. versionadded:: 3.5
334 335 336 337 338

.. function:: IS_LINE_JUNK(line)

   Return true for ignorable lines.  The line *line* is ignorable if *line* is
   blank or contains a single ``'#'``, otherwise it is not ignorable.  Used as a
339
   default for parameter *linejunk* in :func:`ndiff` in older versions.
340 341 342 343 344 345 346 347 348 349 350


.. function:: IS_CHARACTER_JUNK(ch)

   Return true for ignorable characters.  The character *ch* is ignorable if *ch*
   is a space or tab, otherwise it is not ignorable.  Used as a default for
   parameter *charjunk* in :func:`ndiff`.


.. seealso::

351
   `Pattern Matching: The Gestalt Approach <http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970>`_
352
      Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
353
      was published in `Dr. Dobb's Journal <http://www.drdobbs.com/>`_ in July, 1988.
354 355 356 357 358 359 360 361 362 363


.. _sequence-matcher:

SequenceMatcher Objects
-----------------------

The :class:`SequenceMatcher` class has this constructor:


364
.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
365 366 367 368 369 370 371 372 373 374 375 376 377

   Optional argument *isjunk* must be ``None`` (the default) or a one-argument
   function that takes a sequence element and returns true if and only if the
   element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
   equivalent to passing ``lambda x: 0``; in other words, no elements are ignored.
   For example, pass::

      lambda x: x in " \t"

   if you're comparing lines as sequences of characters, and don't want to synch up
   on blanks or hard tabs.

   The optional arguments *a* and *b* are sequences to be compared; both default to
378
   empty strings.  The elements of both sequences must be :term:`hashable`.
379

380 381 382
   The optional argument *autojunk* can be used to disable the automatic junk
   heuristic.

383 384 385
   .. versionadded:: 3.2
      The *autojunk* parameter.

Terry Reedy's avatar
Terry Reedy committed
386
   SequenceMatcher objects get three data attributes: *bjunk* is the
387
   set of elements of *b* for which *isjunk* is ``True``; *bpopular* is the set of
388 389 390 391
   non-junk elements considered popular by the heuristic (if it is not
   disabled); *b2j* is a dict mapping the remaining elements of *b* to a list
   of positions where they occur. All three are reset whenever *b* is reset
   with :meth:`set_seqs` or :meth:`set_seq2`.
Terry Reedy's avatar
Terry Reedy committed
392

Georg Brandl's avatar
Georg Brandl committed
393
   .. versionadded:: 3.2
Terry Reedy's avatar
Terry Reedy committed
394 395
      The *bjunk* and *bpopular* attributes.

396
   :class:`SequenceMatcher` objects have the following methods:
397

398
   .. method:: set_seqs(a, b)
399

400
      Set the two sequences to be compared.
401

402 403 404 405
   :class:`SequenceMatcher` computes and caches detailed information about the
   second sequence, so if you want to compare one sequence against many
   sequences, use :meth:`set_seq2` to set the commonly used sequence once and
   call :meth:`set_seq1` repeatedly, once for each of the other sequences.
406 407


408
   .. method:: set_seq1(a)
409

410 411
      Set the first sequence to be compared.  The second sequence to be compared
      is not changed.
412 413


414
   .. method:: set_seq2(b)
415

416 417
      Set the second sequence to be compared.  The first sequence to be compared
      is not changed.
418 419


420
   .. method:: find_longest_match(alo, ahi, blo, bhi)
421

422
      Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
423

424 425 426 427 428 429 430 431
      If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
      ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
      <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
      k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
      <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
      all maximal matching blocks, return one that starts earliest in *a*, and
      of all those maximal matching blocks that start earliest in *a*, return
      the one that starts earliest in *b*.
432

433 434 435
         >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
         >>> s.find_longest_match(0, 5, 0, 9)
         Match(a=0, b=4, size=5)
436

437 438 439 440 441 442
      If *isjunk* was provided, first the longest matching block is determined
      as above, but with the additional restriction that no junk element appears
      in the block.  Then that block is extended as far as possible by matching
      (only) junk elements on both sides. So the resulting block never matches
      on junk except as identical junk happens to be adjacent to an interesting
      match.
443

444 445 446 447
      Here's the same example as before, but considering blanks to be junk. That
      prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
      second sequence directly.  Instead only the ``'abcd'`` can match, and
      matches the leftmost ``'abcd'`` in the second sequence:
448

449 450 451
         >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
         >>> s.find_longest_match(0, 5, 0, 9)
         Match(a=1, b=0, size=4)
452

453
      If no blocks match, this returns ``(alo, blo, 0)``.
454

455
      This method returns a :term:`named tuple` ``Match(a, b, size)``.
456

457

458
   .. method:: get_matching_blocks()
459

460 461 462
      Return list of triples describing matching subsequences. Each triple is of
      the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``.  The
      triples are monotonically increasing in *i* and *j*.
463

464 465 466 467 468
      The last triple is a dummy, and has the value ``(len(a), len(b), 0)``.  It
      is the only triple with ``n == 0``.  If ``(i, j, n)`` and ``(i', j', n')``
      are adjacent triples in the list, and the second is not the last triple in
      the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
      triples always describe non-adjacent equal blocks.
469

470
      .. XXX Explain why a dummy is used!
471

472
      .. doctest::
473

474 475 476
         >>> s = SequenceMatcher(None, "abxcd", "abcd")
         >>> s.get_matching_blocks()
         [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
477 478


479
   .. method:: get_opcodes()
480

481 482 483 484
      Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
      of the form ``(tag, i1, i2, j1, j2)``.  The first tuple has ``i1 == j1 ==
      0``, and remaining tuples have *i1* equal to the *i2* from the preceding
      tuple, and, likewise, *j1* equal to the previous *j2*.
485

486
      The *tag* values are strings, with these meanings:
487

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
      +---------------+---------------------------------------------+
      | Value         | Meaning                                     |
      +===============+=============================================+
      | ``'replace'`` | ``a[i1:i2]`` should be replaced by          |
      |               | ``b[j1:j2]``.                               |
      +---------------+---------------------------------------------+
      | ``'delete'``  | ``a[i1:i2]`` should be deleted.  Note that  |
      |               | ``j1 == j2`` in this case.                  |
      +---------------+---------------------------------------------+
      | ``'insert'``  | ``b[j1:j2]`` should be inserted at          |
      |               | ``a[i1:i1]``. Note that ``i1 == i2`` in     |
      |               | this case.                                  |
      +---------------+---------------------------------------------+
      | ``'equal'``   | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
      |               | are equal).                                 |
      +---------------+---------------------------------------------+
504

505
      For example::
506

507 508 509 510
        >>> a = "qabxcd"
        >>> b = "abycdf"
        >>> s = SequenceMatcher(None, a, b)
        >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
511 512
        ...     print('{:7}   a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
        ...         tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
513 514 515 516 517
        delete    a[0:1] --> b[0:0]      'q' --> ''
        equal     a[1:3] --> b[0:2]     'ab' --> 'ab'
        replace   a[3:4] --> b[2:3]      'x' --> 'y'
        equal     a[4:6] --> b[3:5]     'cd' --> 'cd'
        insert    a[6:6] --> b[5:6]       '' --> 'f'
518 519


520
   .. method:: get_grouped_opcodes(n=3)
521

522
      Return a :term:`generator` of groups with up to *n* lines of context.
523

524 525 526
      Starting with the groups returned by :meth:`get_opcodes`, this method
      splits out smaller change clusters and eliminates intervening ranges which
      have no changes.
527

528
      The groups are returned in the same format as :meth:`get_opcodes`.
529 530


531
   .. method:: ratio()
532

533 534
      Return a measure of the sequences' similarity as a float in the range [0,
      1].
535

536 537 538
      Where T is the total number of elements in both sequences, and M is the
      number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
      sequences are identical, and ``0.0`` if they have nothing in common.
539

540 541 542 543
      This is expensive to compute if :meth:`get_matching_blocks` or
      :meth:`get_opcodes` hasn't already been called, in which case you may want
      to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
      upper bound.
544 545


546
   .. method:: quick_ratio()
547

548
      Return an upper bound on :meth:`ratio` relatively quickly.
549 550


551
   .. method:: real_quick_ratio()
552

553
      Return an upper bound on :meth:`ratio` very quickly.
554 555 556 557 558


The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although
:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
Christian Heimes's avatar
Christian Heimes committed
559
:meth:`ratio`:
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574

   >>> s = SequenceMatcher(None, "abcd", "bcde")
   >>> s.ratio()
   0.75
   >>> s.quick_ratio()
   0.75
   >>> s.real_quick_ratio()
   1.0


.. _sequencematcher-examples:

SequenceMatcher Examples
------------------------

Terry Reedy's avatar
Terry Reedy committed
575
This example compares two strings, considering blanks to be "junk":
576 577 578 579 580 581 582

   >>> s = SequenceMatcher(lambda x: x == " ",
   ...                     "private Thread currentThread;",
   ...                     "private volatile Thread currentThread;")

:meth:`ratio` returns a float in [0, 1], measuring the similarity of the
sequences.  As a rule of thumb, a :meth:`ratio` value over 0.6 means the
Christian Heimes's avatar
Christian Heimes committed
583
sequences are close matches:
584

585
   >>> print(round(s.ratio(), 3))
586 587 588
   0.866

If you're only interested in where the sequences match,
Christian Heimes's avatar
Christian Heimes committed
589
:meth:`get_matching_blocks` is handy:
590 591

   >>> for block in s.get_matching_blocks():
592
   ...     print("a[%d] and b[%d] match for %d elements" % block)
593
   a[0] and b[0] match for 8 elements
Christian Heimes's avatar
Christian Heimes committed
594
   a[8] and b[17] match for 21 elements
595 596 597 598 599 600 601
   a[29] and b[38] match for 0 elements

Note that the last tuple returned by :meth:`get_matching_blocks` is always a
dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
tuple element (number of elements matched) is ``0``.

If you want to know how to change the first sequence into the second, use
Christian Heimes's avatar
Christian Heimes committed
602
:meth:`get_opcodes`:
603 604

   >>> for opcode in s.get_opcodes():
605
   ...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
606 607
    equal a[0:8] b[0:8]
   insert a[8:8] b[8:17]
Christian Heimes's avatar
Christian Heimes committed
608
    equal a[8:29] b[17:38]
609

610 611 612 613 614 615 616
.. seealso::

   * The :func:`get_close_matches` function in this module which shows how
     simple code building on :class:`SequenceMatcher` can be used to do useful
     work.

   * `Simple version control recipe
617
     <https://code.activestate.com/recipes/576729/>`_ for a small application
618
     built with :class:`SequenceMatcher`.
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634


.. _differ-objects:

Differ Objects
--------------

Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
diffs. To the contrary, minimal diffs are often counter-intuitive, because they
synch up anywhere possible, sometimes accidental matches 100 pages apart.
Restricting synch points to contiguous matches preserves some notion of
locality, at the occasional cost of producing a longer diff.

The :class:`Differ` class has this constructor:


635
.. class:: Differ(linejunk=None, charjunk=None)
636 637 638 639 640 641 642 643 644 645 646 647

   Optional keyword parameters *linejunk* and *charjunk* are for filter functions
   (or ``None``):

   *linejunk*: A function that accepts a single string argument, and returns true
   if the string is junk.  The default is ``None``, meaning that no line is
   considered junk.

   *charjunk*: A function that accepts a single character argument (a string of
   length 1), and returns true if the character is junk. The default is ``None``,
   meaning that no character is considered junk.

648 649 650 651 652 653
   These junk-filtering functions speed up matching to find
   differences and do not cause any differing lines or characters to
   be ignored.  Read the description of the
   :meth:`~SequenceMatcher.find_longest_match` method's *isjunk*
   parameter for an explanation.

654
   :class:`Differ` objects are used (deltas generated) via a single method:
655 656


657
   .. method:: Differ.compare(a, b)
658

659
      Compare two sequences of lines, and generate the delta (a sequence of lines).
660

661 662 663 664 665 666
      Each sequence must contain individual single-line strings ending with
      newlines.  Such sequences can be obtained from the
      :meth:`~io.IOBase.readlines` method of file-like objects.  The delta
      generated also consists of newline-terminated strings, ready to be
      printed as-is via the :meth:`~io.IOBase.writelines` method of a
      file-like object.
667 668 669 670 671 672 673 674 675


.. _differ-examples:

Differ Example
--------------

This example compares two texts. First we set up the texts, sequences of
individual single-line strings ending with newlines (such sequences can also be
676
obtained from the :meth:`~io.BaseIO.readlines` method of file-like objects):
677 678 679 680 681

   >>> text1 = '''  1. Beautiful is better than ugly.
   ...   2. Explicit is better than implicit.
   ...   3. Simple is better than complex.
   ...   4. Complex is better than complicated.
682
   ... '''.splitlines(keepends=True)
683 684 685 686 687 688 689 690
   >>> len(text1)
   4
   >>> text1[0][-1]
   '\n'
   >>> text2 = '''  1. Beautiful is better than ugly.
   ...   3.   Simple is better than complex.
   ...   4. Complicated is better than complex.
   ...   5. Flat is better than nested.
691
   ... '''.splitlines(keepends=True)
692

Christian Heimes's avatar
Christian Heimes committed
693
Next we instantiate a Differ object:
694 695 696 697 698 699 700

   >>> d = Differ()

Note that when instantiating a :class:`Differ` object we may pass functions to
filter out line and character "junk."  See the :meth:`Differ` constructor for
details.

Christian Heimes's avatar
Christian Heimes committed
701
Finally, we compare the two:
702 703 704

   >>> result = list(d.compare(text1, text2))

Christian Heimes's avatar
Christian Heimes committed
705
``result`` is a list of strings, so let's pretty-print it:
706 707 708 709 710 711 712

   >>> from pprint import pprint
   >>> pprint(result)
   ['    1. Beautiful is better than ugly.\n',
    '-   2. Explicit is better than implicit.\n',
    '-   3. Simple is better than complex.\n',
    '+   3.   Simple is better than complex.\n',
Christian Heimes's avatar
Christian Heimes committed
713
    '?     ++\n',
714
    '-   4. Complex is better than complicated.\n',
Christian Heimes's avatar
Christian Heimes committed
715
    '?            ^                     ---- ^\n',
716
    '+   4. Complicated is better than complex.\n',
Christian Heimes's avatar
Christian Heimes committed
717
    '?           ++++ ^                      ^\n',
718 719
    '+   5. Flat is better than nested.\n']

Christian Heimes's avatar
Christian Heimes committed
720
As a single multi-line string it looks like this:
721 722 723 724 725 726 727 728 729 730 731 732 733 734

   >>> import sys
   >>> sys.stdout.writelines(result)
       1. Beautiful is better than ugly.
   -   2. Explicit is better than implicit.
   -   3. Simple is better than complex.
   +   3.   Simple is better than complex.
   ?     ++
   -   4. Complex is better than complicated.
   ?            ^                     ---- ^
   +   4. Complicated is better than complex.
   ?           ++++ ^                      ^
   +   5. Flat is better than nested.

Christian Heimes's avatar
Christian Heimes committed
735 736 737 738 739 740 741 742 743 744

.. _difflib-interface:

A command-line interface to difflib
-----------------------------------

This example shows how to use difflib to create a ``diff``-like utility.
It is also contained in the Python source distribution, as
:file:`Tools/scripts/diff.py`.

745
.. literalinclude:: ../../Tools/scripts/diff.py