• Guido van Rossum's avatar
    Merged revisions 58742-58816 via svnmerge from · 2cc30daa
    Guido van Rossum yazdı
    svn+ssh://pythondev@svn.python.org/python/trunk
    
    ........
      r58745 | georg.brandl | 2007-11-01 10:19:33 -0700 (Thu, 01 Nov 2007) | 2 lines
    
      #1364: os.lstat is available on Windows too, as an alias to os.stat.
    ........
      r58750 | christian.heimes | 2007-11-01 12:48:10 -0700 (Thu, 01 Nov 2007) | 1 line
    
      Backport of import tests for bug http://bugs.python.org/issue1293 and bug http://bugs.python.org/issue1342
    ........
      r58751 | christian.heimes | 2007-11-01 13:11:06 -0700 (Thu, 01 Nov 2007) | 1 line
    
      Removed non ASCII text from test as requested by Guido. Sorry :/
    ........
      r58753 | georg.brandl | 2007-11-01 13:37:02 -0700 (Thu, 01 Nov 2007) | 2 lines
    
      Fix markup glitch.
    ........
      r58757 | gregory.p.smith | 2007-11-01 14:08:14 -0700 (Thu, 01 Nov 2007) | 4 lines
    
      Fix bug introduced in revision 58385.  Database keys could no longer
      have NULL bytes in them.  Replace the errant strdup with a
      malloc+memcpy.  Adds a unit test for the correct behavior.
    ........
      r58758 | gregory.p.smith | 2007-11-01 14:15:36 -0700 (Thu, 01 Nov 2007) | 3 lines
    
      Undo revision 58533 58534 fixes.  Those were a workaround for
      a problem introduced by 58385.
    ........
      r58759 | gregory.p.smith | 2007-11-01 14:17:47 -0700 (Thu, 01 Nov 2007) | 2 lines
    
      false "fix" undone as correct problem was found and fixed.
    ........
      r58765 | mark.summerfield | 2007-11-02 01:24:59 -0700 (Fri, 02 Nov 2007) | 3 lines
    
      Added more file-handling related cross-references.
    ........
      r58766 | nick.coghlan | 2007-11-02 03:09:12 -0700 (Fri, 02 Nov 2007) | 1 line
    
      Fix for bug 1705170 - contextmanager swallowing StopIteration (2.5 backport candidate)
    ........
      r58784 | thomas.heller | 2007-11-02 12:10:24 -0700 (Fri, 02 Nov 2007) | 4 lines
    
      Issue #1292: On alpha, arm, ppc, and s390 linux systems the
      --with-system-ffi configure option defaults to "yes" because the
      bundled libffi sources are too old.
    ........
      r58785 | thomas.heller | 2007-11-02 12:11:23 -0700 (Fri, 02 Nov 2007) | 1 line
    
      Enable the full ctypes c_longdouble tests again.
    ........
      r58796 | georg.brandl | 2007-11-02 13:06:17 -0700 (Fri, 02 Nov 2007) | 4 lines
    
      Make "hashable" a glossary entry and clarify docs on __cmp__, __eq__ and __hash__.
      I hope the concept of hashability is better understandable now.
      Thanks to Tim Hatch for pointing out the flaws here.
    ........
    2cc30daa
difflib.rst 24.9 KB

:mod:`difflib` --- Helpers for computing deltas

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.

This is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a 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" elements (the Ratcliff and Obershelp algorithm doesn't address junk). The same 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.

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.

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:

The following methods are public:

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

SequenceMatcher Objects

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

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 empty strings. The elements of both sequences must be :term:`hashable`.

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

: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.

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 :meth:`ratio`:

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

SequenceMatcher Examples

This example compares two strings, considering blanks to be "junk:"

>>> 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 sequences are close matches:

>>> print(round(s.ratio(), 3))
0.866

If you're only interested in where the sequences match, :meth:`get_matching_blocks` is handy:

>>> for block in s.get_matching_blocks():
...     print("a[%d] and b[%d] match for %d elements" % block)
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 6 elements
a[14] and b[23] match for 15 elements
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 :meth:`get_opcodes`:

>>> for opcode in s.get_opcodes():
...     print("%6s a[%d:%d] b[%d:%d]" % opcode)
 equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
 equal a[8:14] b[17:23]
 equal a[14:29] b[23:38]

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

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:

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.

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

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 obtained from the :meth:`readlines` method of file-like objects):

>>> 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.
... '''.splitlines(1)
>>> 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.
... '''.splitlines(1)

Next we instantiate a Differ object:

>>> 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.

Finally, we compare the two:

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

result is a list of strings, so let's pretty-print it:

>>> 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',
 '?     ++                                \n',
 '-   4. Complex is better than complicated.\n',
 '?            ^                     ---- ^  \n',
 '+   4. Complicated is better than complex.\n',
 '?           ++++ ^                      ^  \n',
 '+   5. Flat is better than nested.\n']

As a single multi-line string it looks like this:

>>> 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.