Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Fix a crash when function-scope recursive alias appears as upper bound
  • Loading branch information
ilevkivskyi committed Apr 30, 2023
commit d94784706ed7d18714e2c19fe489469948daa224
8 changes: 7 additions & 1 deletion mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1110,7 +1110,13 @@ def visit_type_type(self, t: TypeType) -> Type:
return TypeType.make_normalized(self.anal_type(t.item), line=t.line)

def visit_placeholder_type(self, t: PlaceholderType) -> Type:
n = None if not t.fullname else self.api.lookup_fully_qualified(t.fullname)
n = (
None
# No dot in fullname indicates we are at function scope, and recursive
# types are not supported there anyway, so we just give up.
if not t.fullname or "." not in t.fullname
else self.api.lookup_fully_qualified(t.fullname)
)
if not n or isinstance(n.node, PlaceholderNode):
self.api.defer() # Still incomplete
return t
Expand Down
26 changes: 26 additions & 0 deletions test-data/unit/check-recursive-types.test
Original file line number Diff line number Diff line change
Expand Up @@ -897,3 +897,29 @@ Example = NamedTuple("Example", [("rec", List["Example"])])
e: Example
reveal_type(e) # N: Revealed type is "Tuple[builtins.list[...], fallback=__main__.Example]"
[builtins fixtures/tuple.pyi]

[case testRecursiveBoundFunctionScopeNoCrash]
from typing import TypeVar, Union, Dict

def dummy() -> None:
A = Union[str, Dict[str, "A"]] # E: Cannot resolve name "A" (possible cyclic definition) \
# N: Recursive types are not allowed at function scope
T = TypeVar("T", bound=A)

def bar(x: T) -> T:
pass
reveal_type(bar) # N: Revealed type is "def [T <: Union[builtins.str, builtins.dict[builtins.str, Any]]] (x: T`-1) -> T`-1"
[builtins fixtures/dict.pyi]

[case testForwardBoundFunctionScopeWorks]
from typing import TypeVar, Dict

def dummy() -> None:
A = Dict[str, "B"]
B = Dict[str, str]
T = TypeVar("T", bound=A)

def bar(x: T) -> T:
pass
reveal_type(bar) # N: Revealed type is "def [T <: builtins.dict[builtins.str, builtins.dict[builtins.str, builtins.str]]] (x: T`-1) -> T`-1"
[builtins fixtures/dict.pyi]