]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-46553: allow bare typing.ClassVar annotations (#30983)
authorGregory Beauregard <greg@greg.red>
Fri, 28 Jan 2022 16:58:39 +0000 (08:58 -0800)
committerGitHub <noreply@github.com>
Fri, 28 Jan 2022 16:58:39 +0000 (08:58 -0800)
These are used in the wild and covered by dataclasses unit tests.
Several static type checkers support this pattern.

Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2022-01-28-08-47-53.bpo-46553.f7Uc96.rst [new file with mode: 0644]

index 3069331c2a3541fbc9418618ea2737b5f12ee1ba..8449affd03a768acc642ceedeab0756d2c526dde 100644 (file)
@@ -2071,7 +2071,7 @@ class GenericTests(BaseTestCase):
         with self.assertRaises(TypeError):
             Tuple[Optional]
         with self.assertRaises(TypeError):
-            ClassVar[ClassVar]
+            ClassVar[ClassVar[int]]
         with self.assertRaises(TypeError):
             List[ClassVar[int]]
 
@@ -2896,12 +2896,16 @@ class ForwardRefTests(BaseTestCase):
         class C:
             a: Annotated['ClassVar[int]', (3, 5)] = 4
             b: Annotated['Final[int]', "const"] = 4
+            x: 'ClassVar' = 4
+            y: 'Final' = 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])
+        self.assertEqual(get_type_hints(C, globals())['x'], ClassVar)
+        self.assertEqual(get_type_hints(C, globals())['y'], Final)
         with self.assertRaises(TypeError):
             get_type_hints(CF, globals()),
 
index 36b95d70dea5ba65f42efe9686f485a8efbb27b1..232aa1a50d2e53edd7c5e38f8bfd7ddc156f823d 100644 (file)
@@ -173,7 +173,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
     if (isinstance(arg, _GenericAlias) and
             arg.__origin__ in invalid_generic_forms):
         raise TypeError(f"{arg} is not valid as type argument")
-    if arg in (Any, NoReturn, Final):
+    if arg in (Any, NoReturn, ClassVar, Final):
         return arg
     if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
         raise TypeError(f"Plain {arg} is not valid as type argument")
diff --git a/Misc/NEWS.d/next/Library/2022-01-28-08-47-53.bpo-46553.f7Uc96.rst b/Misc/NEWS.d/next/Library/2022-01-28-08-47-53.bpo-46553.f7Uc96.rst
new file mode 100644 (file)
index 0000000..2c03912
--- /dev/null
@@ -0,0 +1 @@
+In :func:`typing.get_type_hints`, support evaluating bare stringified ``ClassVar`` annotations. Patch by Gregory Beauregard.