bpo-40397: Fix subscription of nested generic alias without parameters. (GH-20021)

This commit is contained in:
Serhiy Storchaka 2020-05-10 13:39:40 +03:00 committed by GitHub
parent 86a93fddf7
commit 0122d48681
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 3 deletions

View File

@ -10,7 +10,7 @@ from typing import Any, NoReturn
from typing import TypeVar, AnyStr
from typing import T, KT, VT # Not in __all__.
from typing import Union, Optional, Literal
from typing import Tuple, List, MutableMapping
from typing import Tuple, List, Dict, MutableMapping
from typing import Callable
from typing import Generic, ClassVar, Final, final, Protocol
from typing import cast, runtime_checkable
@ -3173,6 +3173,17 @@ class CollectionsAbcTests(BaseTestCase):
def test_dict(self):
self.assertIsSubclass(dict, typing.Dict)
def test_dict_subscribe(self):
K = TypeVar('K')
V = TypeVar('V')
self.assertEqual(Dict[K, V][str, int], Dict[str, int])
self.assertEqual(Dict[K, int][str], Dict[str, int])
self.assertEqual(Dict[str, V][int], Dict[str, int])
self.assertEqual(Dict[K, List[V]][str, int], Dict[str, List[int]])
self.assertEqual(Dict[K, List[int]][str], Dict[str, List[int]])
self.assertEqual(Dict[K, list[V]][str, int], Dict[str, list[int]])
self.assertEqual(Dict[K, list[int]][str], Dict[str, list[int]])
def test_no_list_instantiation(self):
with self.assertRaises(TypeError):
typing.List()

View File

@ -702,8 +702,10 @@ class _GenericAlias(_BaseGenericAlias, _root=True):
if isinstance(arg, TypeVar):
arg = subst[arg]
elif isinstance(arg, (_GenericAlias, GenericAlias)):
subargs = tuple(subst[x] for x in arg.__parameters__)
arg = arg[subargs]
subparams = arg.__parameters__
if subparams:
subargs = tuple(subst[x] for x in subparams)
arg = arg[subargs]
new_args.append(arg)
return self.copy_with(tuple(new_args))