Module difflib
[hide private]
[frames] | no frames]

Module difflib


Module difflib -- helpers for computing deltas between objects.

Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
    Use SequenceMatcher to return list of the best "good enough" matches.

Function context_diff(a, b):
    For two lists of strings, return a delta in context diff format.

Function ndiff(a, b):
    Return a delta: the difference between `a` and `b` (lists of strings).

Function restore(delta, which):
    Return one of the two sequences that generated an ndiff delta.

Function unified_diff(a, b):
    For two lists of strings, return a delta in unified diff format.

Class SequenceMatcher:
    A flexible class for comparing pairs of sequences of any type.

Class Differ:
    For producing human-readable deltas from sequences of lines of text.

Class HtmlDiff:
    For producing HTML side by side comparison with change highlights.

Classes [hide private]
SequenceMatcher
SequenceMatcher is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable.
Differ
Differ is a class for comparing sequences of lines of text, and producing human-readable differences or deltas.
HtmlDiff
For producing HTML side by side comparison with change highlights.
Functions [hide private]
 
_calculate_ratio(matches, length)
 
get_close_matches(word, possibilities, n=3, cutoff=0.6)
Use SequenceMatcher to return list of the best "good enough" matches.
 
_count_leading(line, ch)
Return number of `ch` characters at the start of `line`.
 
IS_LINE_JUNK(line, pat=<built-in method match of _sre.SRE_Pattern object at 0x40676020>)
Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
 
IS_CHARACTER_JUNK(ch, ws=' \t')
Return 1 for ignorable character: iff `ch` is a space or tab.
 
unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')
Compare two sequences of lines; generate the delta as a unified 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.
 
ndiff(a, b, linejunk=None, charjunk=<function IS_CHARACTER_JUNK at 0x406751ec>)
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
 
_mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=<function IS_CHARACTER_JUNK at 0x406751ec>)
Returns generator yielding marked up from/to side by side differences.
 
restore(delta, which)
Generate one of the two sequences that generated a delta.
 
_test()
Variables [hide private]
  _file_template = '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1...
  _styles = '\n table.diff {font-family:Courier; border:m...
  _table_template = '\n <table class="diff" id="difflib_chg_%...
  _legend = '\n <table class="diff" summary="Legends">\n ...

Imports: heapq


Function Details [hide private]

get_close_matches(word, possibilities, n=3, cutoff=0.6)

 

Use SequenceMatcher to return list of the best "good enough" matches.

word is a sequence for which close matches are desired (typically a string).

possibilities is a list of sequences against which to match word (typically a list of strings).

Optional arg n (default 3) is the maximum number of close matches to return. n must be > 0.

Optional arg cutoff (default 0.6) is a float in [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 list, sorted by similarity score, most similar first.

>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except']

_count_leading(line, ch)

 

Return number of `ch` characters at the start of `line`.

Example:

>>> _count_leading('   abc', ' ')
3

IS_LINE_JUNK(line, pat=<built-in method match of _sre.SRE_Pattern object at 0x40676020>)

 

Return 1 for ignorable line: iff `line` is blank or contains a single '#'.

Examples:

>>> IS_LINE_JUNK('\n')
True
>>> IS_LINE_JUNK('  #   \n')
True
>>> IS_LINE_JUNK('hello\n')
False

IS_CHARACTER_JUNK(ch, ws=' \t')

 

Return 1 for ignorable character: iff `ch` is a space or tab.

Examples:

>>> IS_CHARACTER_JUNK(' ')
True
>>> IS_CHARACTER_JUNK('\t')
True
>>> IS_CHARACTER_JUNK('\n')
False
>>> IS_CHARACTER_JUNK('x')
False

unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')

 

Compare two sequences of lines; generate the delta as a unified diff.

Unified diffs are a compact way of showing line changes and a few lines of context. 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 file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing newlines.

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

The unidiff format normally has a header for filenames and modification times. Any or all of these may be specified using strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the format returned by time.ctime().

Example:

>>> for line in unified_diff('one two three four'.split(),
...             'zero one tree four'.split(), 'Original', 'Current',
...             'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:20:52 2003',
...             lineterm=''):
...     print line
--- Original Sat Jan 26 23:30:50 1991
+++ Current Fri Jun 06 10:20:52 2003
@@ -1,4 +1,4 @@
+zero
 one
-two
-three
+tree
 four

context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\n')

 

Compare two sequences of lines; generate the delta as a context diff.

Context diffs are a compact way of showing line changes and a few lines of context. 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 file.readlines() result in diffs that are suitable for file.writelines() since both the inputs and outputs have trailing 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', 'tofile', 'fromfiledate', and 'tofiledate'. The modification times are normally expressed in the format returned by time.ctime(). If not specified, the strings default to blanks.

Example:

>>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
...       'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current',
...       'Sat Jan 26 23:30:50 1991', 'Fri Jun 06 10:22:46 2003')),
*** Original Sat Jan 26 23:30:50 1991
--- Current Fri Jun 06 10:22:46 2003
***************
*** 1,4 ****
  one
! two
! three
  four
--- 1,4 ----
+ zero
  one
! tree
  four

ndiff(a, b, linejunk=None, charjunk=<function IS_CHARACTER_JUNK at 0x406751ec>)

 

Compare `a` and `b` (lists of strings); return a `Differ`-style delta.

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

- linejunk: A function that should accept a single string argument, and
  return true iff the string is junk.  The default is None, and is
  recommended; as of Python 2.3, an adaptive notion of "noise" lines is
  used that does a good job on its own.

- charjunk: A function that should accept a string of length 1. The
  default is module-level function IS_CHARACTER_JUNK, which filters out
  whitespace characters (a blank or tab; note: bad idea to include newline
  in this!).

Tools/scripts/ndiff.py is a command-line front-end to this function.

Example:

>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
...              'ore\ntree\nemu\n'.splitlines(1))
>>> print ''.join(diff),
- one
?  ^
+ ore
?  ^
- two
- three
?  -
+ tree
+ emu

_mdiff(fromlines, tolines, context=None, linejunk=None, charjunk=<function IS_CHARACTER_JUNK at 0x406751ec>)

 
Returns generator yielding marked up from/to side by side differences.

Arguments:
fromlines -- list of text lines to compared to tolines
tolines -- list of text lines to be compared to fromlines
context -- number of context lines to display on each side of difference,
           if None, all from/to text lines will be generated.
linejunk -- passed on to ndiff (see ndiff documentation)
charjunk -- passed on to ndiff (see ndiff documentation)

This function returns an interator which returns a tuple:
(from line tuple, to line tuple, boolean flag)

from/to line tuple -- (line num, line text)
    line num -- integer or None (to indicate a context seperation)
    line text -- original line text with following markers inserted:
        '+' -- marks start of added text
        '-' -- marks start of deleted text
        '^' -- marks start of changed text
        '' -- marks end of added/deleted/changed text

boolean flag -- None indicates context separation, True indicates
    either "from" or "to" line contains a change, otherwise False.

This function/iterator was originally developed to generate side by side
file difference for making HTML pages (see HtmlDiff class for example
usage).

Note, this function utilizes the ndiff function to generate the side by
side difference markup.  Optional ndiff arguments may be passed to this
function and they in turn will be passed to ndiff.

restore(delta, which)

 

Generate one of the two sequences that generated a delta.

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

Examples:

>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
...              'ore\ntree\nemu\n'.splitlines(1))
>>> diff = list(diff)
>>> print ''.join(restore(diff, 1)),
one
two
three
>>> print ''.join(restore(diff, 2)),
ore
tree
emu

Variables Details [hide private]

_file_template

Value:
'''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<head>
    <meta http-equiv="Content-Type"
...

_styles

Value:
'''
        table.diff {font-family:Courier; border:medium;}
        .diff_header {background-color:#e0e0e0}
        td.diff_header {text-align:right}
        .diff_next {background-color:#c0c0c0}
        .diff_add {background-color:#aaffaa}
        .diff_chg {background-color:#ffff77}
        .diff_sub {background-color:#ffaaaa}'''

_table_template

Value:
'''
    <table class="diff" id="difflib_chg_%(prefix)s_top"
           cellspacing="0" cellpadding="0" rules="groups" >
        <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgro\
up>
        <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgro\
up>
        %(header_row)s
...

_legend

Value:
'''
    <table class="diff" summary="Legends">
        <tr> <th colspan="2"> Legends </th> </tr>
        <tr> <td> <table border="" summary="Colors">
                      <tr><th> Colors </th> </tr>
                      <tr><td class="diff_add">&nbsp;Added&nbsp;</td><\
/tr>
                      <tr><td class="diff_chg">Changed</td> </tr>
...