Skip to content

Commit bfcb414

Browse files
bpo-46539: Pass status of special typeforms to forward references (GH-30926)
Previously this didn't matter because there weren't any valid code paths that could trigger a type check with a special form, but after the bug fix for `Annotated` wrapping special forms it's now possible to annotate something like `Annotated['ClassVar[int]', (3, 4)]`. This change would also be needed for proposed future changes, such as allowing `ClassVar` and `Final` to nest each other in dataclasses. (cherry picked from commit ced5005) Co-authored-by: Gregory Beauregard <greg@greg.red>
1 parent 486a4b3 commit bfcb414

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

Lib/test/test_typing.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2809,6 +2809,20 @@ def foo(a: 'Callable[..., T]'):
28092809
self.assertEqual(get_type_hints(foo, globals(), locals()),
28102810
{'a': Callable[..., T]})
28112811

2812+
def test_special_forms_forward(self):
2813+
2814+
class C:
2815+
a: Annotated['ClassVar[int]', (3, 5)] = 4
2816+
b: Annotated['Final[int]', "const"] = 4
2817+
2818+
class CF:
2819+
b: List['Final[int]'] = 4
2820+
2821+
self.assertEqual(get_type_hints(C, globals())['a'], ClassVar[int])
2822+
self.assertEqual(get_type_hints(C, globals())['b'], Final[int])
2823+
with self.assertRaises(TypeError):
2824+
get_type_hints(CF, globals()),
2825+
28122826
def test_syntax_error(self):
28132827

28142828
with self.assertRaises(SyntaxError):

Lib/typing.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -134,12 +134,12 @@
134134
# legitimate imports of those modules.
135135

136136

137-
def _type_convert(arg, module=None):
137+
def _type_convert(arg, module=None, *, allow_special_forms=False):
138138
"""For converting None to type(None), and strings to ForwardRef."""
139139
if arg is None:
140140
return type(None)
141141
if isinstance(arg, str):
142-
return ForwardRef(arg, module=module)
142+
return ForwardRef(arg, module=module, is_class=allow_special_forms)
143143
return arg
144144

145145

@@ -161,7 +161,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
161161
if is_argument:
162162
invalid_generic_forms += (Final,)
163163

164-
arg = _type_convert(arg, module=module)
164+
arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
165165
if (isinstance(arg, _GenericAlias) and
166166
arg.__origin__ in invalid_generic_forms):
167167
raise TypeError(f"{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 stringified ``ClassVar`` and ``Final`` annotations inside ``Annotated``. Patch by Gregory Beauregard.

0 commit comments

Comments
 (0)