8000 Add a `color: bool` arg to `difflib.unified_diff` · Issue #133722 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
dougthor42 opened this issue May 9, 2025 · 0 comments · May be fixed by #133725
Open

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

dougthor42 opened this issue May 9, 2025 · 0 comments · May be fixed by #133725
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement

Comments

@dougthor42
Copy link
Contributor
dougthor42 commented May 9, 2025

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

@dougthor42 dougthor42 added the type-feature A feature request or enhancement label May 9, 2025
dougthor42 added a commit to dougthor42/cpython that referenced this issue May 9, 2025
@picnixz picnixz added the stdlib Python modules in the Lib dir label May 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stdlib Python modules in the Lib dir type-feature A feature request or enhancement
Projects
None yet
2 participants
0