Skip to content

Commit 655ad1c

Browse files
[3.14] pythongh-138318, PyREPL: builtins should not be highlighted when used as attribute names (pythonGH-138319) (python#138654)
pythongh-138318, PyREPL: builtins should not be highlighted when used as attribute names (pythonGH-138319) (cherry picked from commit 7a3bca5) Co-authored-by: yihong <[email protected]>
1 parent 5074241 commit 655ad1c

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

Lib/_pyrepl/utils.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,10 @@ def gen_colors_from_token_stream(
208208
):
209209
span = Span.from_token(token, line_lengths)
210210
yield ColorSpan(span, "soft_keyword")
211-
elif token.string in BUILTINS:
211+
elif (
212+
token.string in BUILTINS
213+
and not (prev_token and prev_token.exact_type == T.DOT)
214+
):
212215
span = Span.from_token(token, line_lengths)
213216
yield ColorSpan(span, "builtin")
214217

Lib/test/test_pyrepl/test_utils.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from unittest import TestCase
22

3-
from _pyrepl.utils import str_width, wlen, prev_next_window
3+
from _pyrepl.utils import str_width, wlen, prev_next_window, gen_colors
44

55

66
class TestUtils(TestCase):
@@ -60,3 +60,25 @@ def gen_raise():
6060
self.assertEqual(next(pnw), (3, 4, None))
6161
with self.assertRaises(ZeroDivisionError):
6262
next(pnw)
63+
64+
def test_gen_colors_keyword_highlighting(self):
65+
cases = [
66+
# no highlights
67+
("a.set", [(".", "op")]),
68+
("obj.list", [(".", "op")]),
69+
("obj.match", [(".", "op")]),
70+
("b. \\\n format", [(".", "op")]),
71+
# highlights
72+
("set", [("set", "builtin")]),
73+
("list", [("list", "builtin")]),
74+
(" \n dict", [("dict", "builtin")]),
75+
]
76+
for code, expected_highlights in cases:
77+
with self.subTest(code=code):
78+
colors = list(gen_colors(code))
79+
# Extract (text, tag) pairs for comparison
80+
actual_highlights = []
81+
for color in colors:
82+
span_text = code[color.span.start:color.span.end + 1]
83+
actual_highlights.append((span_text, color.tag))
84+
self.assertEqual(actual_highlights, expected_highlights)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
The default REPL now avoids highlighting built-in names (for instance :class:`set`
2+
or :func:`format`) when they are used as attribute names (for instance in ``value.set``
3+
or ``text.format``).

0 commit comments

Comments
 (0)