Skip to content

Commit f6c4dd9

Browse files
committed
Skip colour for non-Python <repr>
1 parent d907d38 commit f6c4dd9

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

Lib/pprint.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,13 @@ def _colorize_output(text):
145145
# (for example, from a custom __repr__),
146146
# return as-is to avoid breaking their color.
147147
return text
148-
colors = list(gen_colors(text))
148+
# Skip coloring inside <...> reprs (for example, <built-in function print>),
149+
# they're placeholders, not Python source.
150+
skip = [m.span() for m in re.finditer(r"<[^<>\n]*>", text)]
151+
colors = [
152+
c for c in gen_colors(text)
153+
if not any(start <= c.span.start < end for start, end in skip)
154+
]
149155
chars, _ = disp_str(text, colors=colors, force_color=True, escape=False)
150156
return "".join(chars)
151157

Lib/test/test_pprint.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,24 @@ def __repr__(self):
269269
expected = "{'a': \x1b[31mred\x1b[0m, 'b': 42, 'c': 'hello'}\n"
270270
self.assertEqual(result, expected)
271271

272+
def test_color_skips_placeholder_reprs(self):
273+
"""<...> reprs are non-literal placeholders, not Python source,
274+
so their contents must not be tokenized and colored."""
275+
recursive = [1, "two", None]
276+
recursive.append(recursive)
277+
278+
with unittest.mock.patch.dict(
279+
"os.environ", {"FORCE_COLOR": "1", "NO_COLOR": ""}
280+
):
281+
stream = io.StringIO()
282+
pprint.pprint(recursive, stream=stream, color=True)
283+
result = stream.getvalue()
284+
285+
self.assertIn("\x1b[", result) # surrounding output is still colored
286+
match = re.search(r"<[^<>\n]*>", result)
287+
self.assertIsNotNone(match)
288+
self.assertNotIn("\x1b[", match.group(0))
289+
272290
def test_basic(self):
273291
# Verify .isrecursive() and .isreadable() w/o recursion
274292
pp = pprint.PrettyPrinter()

0 commit comments

Comments
 (0)