r""" 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 sequences of characters within similar (near-matching) lines. Each line of a Diffe
| 725 | |
| 726 | |
| 727 | class Differ: |
| 728 | r""" |
| 729 | Differ is a class for comparing sequences of lines of text, and |
| 730 | producing human-readable differences or deltas. Differ uses |
| 731 | SequenceMatcher both to compare sequences of lines, and to compare |
| 732 | sequences of characters within similar (near-matching) lines. |
| 733 | |
| 734 | Each line of a Differ delta begins with a two-letter code: |
| 735 | |
| 736 | '- ' line unique to sequence 1 |
| 737 | '+ ' line unique to sequence 2 |
| 738 | ' ' line common to both sequences |
| 739 | '? ' line not present in either input sequence |
| 740 | |
| 741 | Lines beginning with '? ' attempt to guide the eye to intraline |
| 742 | differences, and were not present in either input sequence. These lines |
| 743 | can be confusing if the sequences contain tab characters. |
| 744 | |
| 745 | Note that Differ makes no claim to produce a *minimal* diff. To the |
| 746 | contrary, minimal diffs are often counter-intuitive, because they synch |
| 747 | up anywhere possible, sometimes accidental matches 100 pages apart. |
| 748 | Restricting synch points to contiguous matches preserves some notion of |
| 749 | locality, at the occasional cost of producing a longer diff. |
| 750 | |
| 751 | Example: Comparing two texts. |
| 752 | |
| 753 | First we set up the texts, sequences of individual single-line strings |
| 754 | ending with newlines (such sequences can also be obtained from the |
| 755 | `readlines()` method of file-like objects): |
| 756 | |
| 757 | >>> text1 = ''' 1. Beautiful is better than ugly. |
| 758 | ... 2. Explicit is better than implicit. |
| 759 | ... 3. Simple is better than complex. |
| 760 | ... 4. Complex is better than complicated. |
| 761 | ... '''.splitlines(keepends=True) |
| 762 | >>> len(text1) |
| 763 | 4 |
| 764 | >>> text1[0][-1] |
| 765 | '\n' |
| 766 | >>> text2 = ''' 1. Beautiful is better than ugly. |
| 767 | ... 3. Simple is better than complex. |
| 768 | ... 4. Complicated is better than complex. |
| 769 | ... 5. Flat is better than nested. |
| 770 | ... '''.splitlines(keepends=True) |
| 771 | |
| 772 | Next we instantiate a Differ object: |
| 773 | |
| 774 | >>> d = Differ() |
| 775 | |
| 776 | Note that when instantiating a Differ object we may pass functions to |
| 777 | filter out line and character 'junk'. See Differ.__init__ for details. |
| 778 | |
| 779 | Finally, we compare the two: |
| 780 | |
| 781 | >>> result = list(d.compare(text1, text2)) |
| 782 | |
| 783 | 'result' is a list of strings, so let's pretty-print it: |
| 784 |
no outgoing calls
no test coverage detected
searching dependent graphs…