[Python-checkins] bpo-43224: Forbid TypeVar substitution with Unpack (GH-32031)
JelleZijlstra
webhook-mailer at python.org
Tue Apr 12 23:09:13 EDT 2022
https://github.com/python/cpython/commit/15537c51c188a6633248c25d211d5216e673aee3
commit: 15537c51c188a6633248c25d211d5216e673aee3
branch: main
author: Serhiy Storchaka <storchaka at gmail.com>
committer: JelleZijlstra <jelle.zijlstra at gmail.com>
date: 2022-04-12T20:08:49-07:00
summary:
bpo-43224: Forbid TypeVar substitution with Unpack (GH-32031)
files:
M Lib/test/test_typing.py
M Lib/typing.py
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 2afa5449bc2e6..97fc66a2f748f 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -562,6 +562,20 @@ class G(Generic[Unpack[Ts]]): pass
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')
diff --git a/Lib/typing.py b/Lib/typing.py
index 46fc72218dceb..1b584bea0c3e5 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -965,6 +965,8 @@ def __init__(self, name, *constraints, bound=None,
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
More information about the Python-checkins
mailing list