Skip to content

Commit f941512

Browse files
[3.13] gh-151471: Colorize the soft keyword type in IDLE (GH-151700) (GH-157993)
`type` is now colored as a keyword when it starts a statement and is followed by a name, as in `type Point = tuple[float, float]`. It stays a builtin elsewhere, for example in `type = type(1)`, `type(x)` or `type in (int, str)`. (cherry picked from commit 68ed7a5) Co-authored-by: Locked-chess-official <13140752715@163.com>
1 parent 625b044 commit f941512

3 files changed

Lines changed: 23 additions & 1 deletion

File tree

Lib/idlelib/colorizer.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ def make_pat():
4242
]) +
4343
r"))"
4444
)
45+
type_softkw = (
46+
r"^[ \t]*" + # at beginning of line + possible indentation
47+
r"(?P<TYPE_SOFTKW>type)" +
48+
r"(?=[ \t]+(?!(?:" + "|".join(keyword.kwlist) + r")\b)[^\W\d])"
49+
)
4550
builtinlist = [str(name) for name in dir(builtins)
4651
if not name.startswith('_') and
4752
name not in keyword.kwlist]
@@ -54,7 +59,7 @@ def make_pat():
5459
dq3string = stringprefix + r'"""[^"\\]*((\\.|"(?!""))[^"\\]*)*(""")?'
5560
string = any("STRING", [sq3string, dq3string, sqstring, dqstring])
5661
prog = re.compile("|".join([
57-
builtin, comment, string, kw,
62+
type_softkw, builtin, comment, string, kw,
5863
match_softkw, case_default,
5964
case_softkw_and_pattern,
6065
any("SYNC", [r"\n"]),
@@ -70,6 +75,7 @@ def make_pat():
7075
"CASE_SOFTKW": "KEYWORD",
7176
"CASE_DEFAULT_UNDERSCORE": "KEYWORD",
7277
"CASE_SOFTKW2": "KEYWORD",
78+
"TYPE_SOFTKW": "KEYWORD",
7379
}
7480

7581

Lib/idlelib/idle_test/test_colorizer.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,21 @@ def test_def_statement(self):
480480
# def followed by non-keyword
481481
self._assert_highlighting('def ++', {'KEYWORD': [('1.0', '1.3')]})
482482

483+
def test_type_soft_keyword(self):
484+
# type as a soft keyword
485+
self._assert_highlighting('type X = int',
486+
{'KEYWORD': [('1.0', '1.4')],
487+
'BUILTIN': [('1.9', '1.12')]})
488+
# type as a name
489+
self._assert_highlighting('type = type(1)',
490+
{'BUILTIN': [('1.0', '1.4'), ('1.7', '1.11')]})
491+
self._assert_highlighting('type(x)',
492+
{'BUILTIN': [('1.0', '1.4')]})
493+
self._assert_highlighting('type in (int, str)',
494+
{'KEYWORD': [('1.5', '1.7')],
495+
'BUILTIN': [('1.0', '1.4'), ('1.9', '1.12'),
496+
('1.14', '1.17')]})
497+
483498
def test_match_soft_keyword(self):
484499
# empty match
485500
self._assert_highlighting('match', {'KEYWORD': [('1.0', '1.5')]})
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Colorize the soft keyword ``type`` in IDLE.

0 commit comments

Comments
 (0)