Reputation: 12452
import difflib
test1 = ")\n )"
test2 = "#)\n #)"
d = difflib.Differ()
diff = d.compare(test1.splitlines(), test2.splitlines())
print "\n".join(diff)
OUTPUT:
- )
+ #)
- )
+ #)
? +
as you can see, it didnt detect the change for the first line ( no ?
line )but it did in the second line
Anyone know why difflib think its a delete/add, and not change?
Upvotes: 1
Views: 396
Reputation: 4715
One-character string is an edge case. For two or more characters, insertion of one character is always detected correctly. Here is a simple algorithm to demonstrate that:
import difflib
def show_diffs(limit):
characters = 'abcdefghijklmnopqrstuvwxyz'
differ = difflib.Differ()
for length in range(1, limit + 1):
for pos in range(0, length + 1):
line_a = characters[:length]
line_b = line_a[:pos] + 'A' + line_a[pos:]
diff = list(differ.compare([line_a], [line_b]))
if len(diff) == 2 and diff[0][0] == '-' and diff[1][0] == '+':
marker = 'N' # Insertion not detected
elif len(diff) == 3 and diff[0][0] == '-' and diff[1][0] == '+' and diff[2][0] == '?':
marker = 'Y' # Insertion detected
else:
print('ERROR: unexpected diff for %r -> %r:\n%r' % (line_a, line_b, diff))
return
print('%s %r -> %r' % (marker, line_a, line_b))
show_diffs(limit=3)
It "fails" only for 1-character strings:
N 'a' -> 'Aa'
N 'a' -> 'aA'
Y 'ab' -> 'Aab'
Y 'ab' -> 'aAb'
Y 'ab' -> 'abA'
Y 'abc' -> 'Aabc'
Y 'abc' -> 'aAbc'
Y 'abc' -> 'abAc'
Y 'abc' -> 'abcA'
Upvotes: 2