8000 bpo-46553: allow bare typing.ClassVar annotations (#30983) · python/cpython@5445e17 · GitHub
[go: up one dir, main page]

Skip to content

Commit 5445e17

Browse files
authored
bpo-46553: allow bare typing.ClassVar annotations (#30983)
These are used in the wild and covered by dataclasses unit tests. Several static type checkers support this pattern.
1 parent 45faf15 commit 5445e17

File tree

3 files changed

+7
-2
lines changed

3 files changed

+7
-2
lines changed

Lib/test/test_typing.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2071,7 +2071,7 @@ def test_fail_with_bare_union(self):
20712071
with self.assertRaises(TypeError):
20722072
Tuple[Optional]
20732073
with self.assertRaises(TypeError):
2074-
ClassVar[ClassVar]
2074+
ClassVar[ClassVar[int]]
20752075
with self.assertRaises(TypeError):
20762076
List[ClassVar[int]]
20772077

@@ -2896,12 +2896,16 @@ def test_special_forms_forward(self):
28962896
class C:
28972897
a: Annotated['ClassVar[int]', (3, 5)] = 4
28982898
b: Annotated['Final[int]', "const"] = 4
2899+
x: 'ClassVar' = 4
2900+
y: 'Final' = 4
28992901

29002902
class CF:
29012903
b: List['Final[int]'] = 4
29022904

29032905
self.assertEqual(get_type_hints(C, globals())['a'], ClassVar[int])
29042906
self.assertEqual(get_type_hints(C, globals())['b'], Final[int])
2907+
self.assertEqual(get_type_hints(C, globals())['x'], ClassVar)
2908+
self.assertEqual(get_type_hints(C, globals())['y'], Final)
29052909
with self.assertRaises(TypeError):
29062910
get_type_hints(CF, globals()),
29072911

Lib/typing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
173173
if (isinstance(arg, _GenericAlias) and
174174
arg.__origin__ in invalid_generic_forms):
175175
raise TypeError(f"{arg} is not valid as type argument")
176-
if arg in (Any, NoReturn, Final):
176+
if arg in (Any, NoReturn, ClassVar, Final):
177177
return arg
178178
if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
179179
raise TypeError(f"Plain {arg} is not valid as type argument")
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
In :func:`typing.get_type_hints`, support evaluating bare stringified ``ClassVar`` annotations. Patch by Gregory Beauregard.

0 commit comments

Comments
 (0)
0