Skip to content

Commit cb78994

Browse files
Add more tests for variable substitution in generics (GH-31170)
(cherry picked from commit 3da5526) Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent c88407c commit cb78994

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Lib/test/test_typing.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,15 @@ def test_no_bivariant(self):
247247
with self.assertRaises(ValueError):
248248
TypeVar('T', covariant=True, contravariant=True)
249249

250+
def test_bad_var_substitution(self):
251+
T = TypeVar('T')
252+
for arg in (), (int, str):
253+
with self.subTest(arg=arg):
254+
with self.assertRaises(TypeError):
255+
List[T][arg]
256+
with self.assertRaises(TypeError):
257+
list[T][arg]
258+
250259

251260
class UnionTests(BaseTestCase):
252261

@@ -560,8 +569,11 @@ def test_var_substitution(self):
560569
C2 = Callable[[KT, T], VT]
561570
C3 = Callable[..., T]
562571
self.assertEqual(C1[str], Callable[[int, str], str])
572+
if Callable is typing.Callable:
573+
self.assertEqual(C1[None], Callable[[int, type(None)], type(None)])
563574
self.assertEqual(C2[int, float, str], Callable[[int, float], str])
564575
self.assertEqual(C3[int], Callable[..., int])
576+
self.assertEqual(C3[NoReturn], Callable[..., NoReturn])
565577

566578
# multi chaining
567579
C4 = C2[int, VT, str]
@@ -4880,6 +4892,17 @@ class X(Generic[P, P2]):
48804892
self.assertEqual(G1.__args__, ((int, str), (bytes,)))
48814893
self.assertEqual(G2.__args__, ((int,), (str, bytes)))
48824894

4895+
def test_bad_var_substitution(self):
4896+
T = TypeVar('T')
4897+
P = ParamSpec('P')
4898+
bad_args = (42, int, None, T, int|str, Union[int, str])
4899+
for arg in bad_args:
4900+
with self.subTest(arg=arg):
4901+
with self.assertRaises(TypeError):
4902+
typing.Callable[P, T][arg, str]
4903+
with self.assertRaises(TypeError):
4904+
collections.abc.Callable[P, T][arg, str]
4905+
48834906
def test_no_paramspec_in__parameters__(self):
48844907
# ParamSpec should not be found in __parameters__
48854908
# of generics. Usages outside Callable, Concatenate
@@ -4909,6 +4932,10 @@ def test_paramspec_in_nested_generics(self):
49094932
self.assertEqual(G1.__parameters__, (P, T))
49104933
self.assertEqual(G2.__parameters__, (P, T))
49114934
self.assertEqual(G3.__parameters__, (P, T))
4935+
C = Callable[[int, str], float]
4936+
self.assertEqual(G1[[int, str], float], List[C])
4937+
self.assertEqual(G2[[int, str], float], list[C])
4938+
self.assertEqual(G3[[int, str], float], list[C] | int)
49124939

49134940

49144941
class ConcatenateTests(BaseTestCase):

0 commit comments

Comments
 (0)