bpo-43224: Forbid TypeVar substitution with Unpack (GH-32031)

This commit is contained in:
Serhiy Storchaka 2022-04-13 06:08:49 +03:00 • committed by GitHub
parent 0859368335
commit 15537c51c1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 0 deletions

View 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')

View 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