]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-43224: Forbid TypeVar substitution with Unpack (GH-32031)
authorSerhiy Storchaka <storchaka@gmail.com>
Wed, 13 Apr 2022 03:08:49 +0000 (06:08 +0300)
committerGitHub <noreply@github.com>
Wed, 13 Apr 2022 03:08:49 +0000 (20:08 -0700)
Lib/test/test_typing.py
Lib/typing.py

index 2afa5449bc2e6f122bf61210daf9d3023734d992..97fc66a2f748f36f84babc8949b3d7b405d6ff92 100644 (file)
@@ -562,6 +562,20 @@ class TypeVarTupleTests(BaseTestCase):
             self.assertEqual(E[float, str, int, bytes],
                              Tuple[List[float], A[str, int], List[bytes]])
 
+    def test_bad_var_substitution(self):
+        Ts = TypeVarTuple('Ts')
+        T = TypeVar('T')
+        T2 = TypeVar('T2')
+        class G(Generic[Unpack[Ts]]): pass
+
+        for A in G, Tuple:
+            B = A[T, Unpack[Ts], str, T2]
+            with self.assertRaises(TypeError):
+                B[int, Unpack[Ts]]
+            C = A[T, Unpack[Ts], str, T2]
+            with self.assertRaises(TypeError):
+                C[int, Unpack[Ts], Unpack[Ts]]
+
     def test_repr_is_correct(self):
         Ts = TypeVarTuple('Ts')
         self.assertEqual(repr(Ts), 'Ts')
index 46fc72218dceb962a50209f342b7e10a93136816..1b584bea0c3e57df5b27e277304de02aa8d429ba 100644 (file)
@@ -965,6 +965,8 @@ class TypeVar(_Final, _Immutable, _BoundVarianceMixin, _root=True):
     def __typing_subst__(self, arg):
         msg = "Parameters to generic types must be types."
         arg = _type_check(arg, msg, is_argument=True)
+        if (isinstance(arg, _GenericAlias) and arg.__origin__ is Unpack):
+            raise TypeError(f"{arg} is not valid as type argument")
         return arg