Skip to content

Add a color: bool arg to difflib.unified_diff #133722

@dougthor42

Description

@dougthor42

Feature or enhancement

Proposal:

What are people's thoughts on adding a color: bool arg to difflib.unified_diff so that it injects ANSI terminal codes to color things in the way that git diff would?

New API:

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

Open questions:

  1. Should the colors be configurable? Eg via dict colors={"equal": "\033[31;1;4m", "delete": "...", "insert": "...", "header": "...", "hunk": "..."}
    • The default would be the basic 4bit colors used by git diff.:
      • header: bold \033[1m
      • hunk lines: cyan \033[36m
      • removed: red \033[31m
      • added: green \033[32m
      • equal: no formatting
    • This might be useful for nonstandard terminal colors?
  2. Should this be added to other functions like ndiff and contextdiff?

I'd be happy to tackle this. Excluding tests, it looks to be O(20 LOC) changes.


Image

$ cat python mydiff.py 
cat: python: No such file or directory
import difflib
import pathlib

file1 = pathlib.Path("a.txt")
file2 = pathlib.Path("b.txt")
udiff = difflib.unified_diff(
    file1.read_text().splitlines(),
    file2.read_text().splitlines(),
    fromfile=str(file1),
    tofile=str(file2),
)
for line in udiff:
    print(line)
$ python mydiff.py 
--- a.txt

+++ b.txt

@@ -1,3 +1,3 @@

 1a
-2b
 3c
+4d

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibPython modules in the Lib dirtype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions