Skip to content

Commit 652b9bb

Browse files
committed
Resolve GenericType nodes better in LookupLocalTypes.
For python/typeshed#7680. PiperOrigin-RevId: 447596238
1 parent c40716d commit 652b9bb

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

pytype/load_pytd_test.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -600,6 +600,18 @@ def test_bad_parameterization(self):
600600
Strings = a.Alias[str, str]
601601
""")
602602

603+
def test_parameterize_twice(self):
604+
ast = self._import(a="""
605+
from typing import AnyStr, Generic
606+
class Foo(Generic[AnyStr]): ...
607+
""", b="""
608+
import a
609+
from typing import AnyStr
610+
x: Foo[str]
611+
Foo = a.Foo[AnyStr]
612+
""")
613+
self.assertEqual(pytd_utils.Print(ast.Lookup("b.x").type), "a.Foo[str]")
614+
603615

604616
_Module = collections.namedtuple("_", ["module_name", "file_name"])
605617

pytype/pytd/visitors.py

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,18 @@ def MaybeSubstituteParameters(base_type, parameters=None):
329329
return base_type.Visit(ReplaceTypeParameters(mapping))
330330

331331

332+
def _MaybeSubstituteParametersInGenericType(node):
333+
if isinstance(node.base_type, (pytd.GenericType, pytd.UnionType)):
334+
try:
335+
node = MaybeSubstituteParameters(
336+
node.base_type, node.parameters) or node
337+
except ValueError as e:
338+
raise KeyError(str(e)) from e
339+
elif isinstance(node.base_type, pytd.AnythingType):
340+
return node.base_type
341+
return node
342+
343+
332344
class LookupExternalTypes(_RemoveTypeParametersFromGenericAny, _ToTypeVisitor):
333345
"""Look up NamedType pointers using a symbol table."""
334346

@@ -482,13 +494,7 @@ def VisitClassType(self, t):
482494
return new_type
483495

484496
def VisitGenericType(self, node):
485-
if isinstance(node.base_type, (pytd.GenericType, pytd.UnionType)):
486-
try:
487-
node = MaybeSubstituteParameters(
488-
node.base_type, node.parameters) or node
489-
except ValueError as e:
490-
raise KeyError(str(e)) from e
491-
return node
497+
return _MaybeSubstituteParametersInGenericType(node)
492498

493499
def _ModulePrefix(self):
494500
return self.name + "." if self.name else ""
@@ -757,6 +763,9 @@ def VisitClassType(self, t):
757763
t.cls = cast(pytd.ClassType, self.VisitNamedType(lookup_type)).cls
758764
return t
759765

766+
def VisitGenericType(self, node):
767+
return _MaybeSubstituteParametersInGenericType(node)
768+
760769

761770
class ReplaceTypes(Visitor):
762771
"""Visitor for replacing types in a tree.

0 commit comments

Comments
 (0)