summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorGregory Beauregard <greg@greg.red>2022-01-27 03:11:51 (GMT)
committerGitHub <noreply@github.com>2022-01-27 03:11:51 (GMT)
commitced50051bb752a7c1e616f4b0c001f37f0354f32 (patch)
tree4a7aa2eaba20f2da05fdff0d31d58f48544ab9d5 /Lib
parent6b491b9dc0b0fdfd1f07ea4e2151236186d8e7e6 (diff)
downloadcpython-ced50051bb752a7c1e616f4b0c001f37f0354f32.zip
cpython-ced50051bb752a7c1e616f4b0c001f37f0354f32.tar.gz
cpython-ced50051bb752a7c1e616f4b0c001f37f0354f32.tar.bz2
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.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/test/test_typing.py14
-rw-r--r--Lib/typing.py6
2 files changed, 17 insertions, 3 deletions
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index b5767d0..4b260d4 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -2870,6 +2870,20 @@ class ForwardRefTests(BaseTestCase):
self.assertEqual(get_type_hints(foo, globals(), locals()),
{'a': Callable[..., T]})
+ def test_special_forms_forward(self):
+
+ class C:
+ a: Annotated['ClassVar[int]', (3, 5)] = 4
+ b: Annotated['Final[int]', "const"] = 4
+
+ class CF:
+ b: List['Final[int]'] = 4
+
+ self.assertEqual(get_type_hints(C, globals())['a'], ClassVar[int])
+ self.assertEqual(get_type_hints(C, globals())['b'], Final[int])
+ with self.assertRaises(TypeError):
+ get_type_hints(CF, globals()),
+
def test_syntax_error(self):
with self.assertRaises(SyntaxError):
diff --git a/Lib/typing.py b/Lib/typing.py
index e3e098b..450cd7b 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -142,12 +142,12 @@ __all__ = [
# legitimate imports of those modules.
-def _type_convert(arg, module=None):
+def _type_convert(arg, module=None, *, allow_special_forms=False):
"""For converting None to type(None), and strings to ForwardRef."""
if arg is None:
return type(None)
if isinstance(arg, str):
- return ForwardRef(arg, module=module)
+ return ForwardRef(arg, module=module, is_class=allow_special_forms)
return arg
@@ -169,7 +169,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
if is_argument:
invalid_generic_forms += (Final,)
- arg = _type_convert(arg, module=module)
+ arg = _type_convert(arg, module=module, allow_special_forms=allow_special_forms)
if (isinstance(arg, _GenericAlias) and
arg.__origin__ in invalid_generic_forms):
raise TypeError(f"{arg} is not valid as type argument")