Skip to content

Commit

Permalink
Fix crash in Self type on forward reference in upper bound (#14206)
Browse files Browse the repository at this point in the history
Fixes #14199 

This is straightforward, just use the same logic as for regular (user
defined) type variables.
  • Loading branch information
ilevkivskyi authored Nov 28, 2022
1 parent 00ee7d5 commit 365297c
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,11 @@ def setup_self_type(self) -> None:
assert self.type is not None
info = self.type
if info.self_type is not None:
return
if has_placeholder(info.self_type.upper_bound):
# Similar to regular (user defined) type variables.
self.defer(force_progress=True)
else:
return
info.self_type = TypeVarType("Self", f"{info.fullname}.Self", 0, [], fill_typevars(info))

def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:
Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-classes.test
Original file line number Diff line number Diff line change
Expand Up @@ -7679,3 +7679,18 @@ def g(b: Type[Any]) -> None:

def h(b: type) -> None:
class D(b): ...

[case testNoCrashOnSelfWithForwardRefGenericClass]
from typing import Generic, Sequence, TypeVar, Self

_T = TypeVar('_T', bound="Foo")

class Foo:
foo: int

class Element(Generic[_T]):
elements: Sequence[Self]

class Bar(Foo): ...
e: Element[Bar]
reveal_type(e.elements) # N: Revealed type is "typing.Sequence[__main__.Element[__main__.Bar]]"
20 changes: 20 additions & 0 deletions test-data/unit/check-dataclasses.test
Original file line number Diff line number Diff line change
Expand Up @@ -1981,3 +1981,23 @@ def const_two(x: T) -> str:
c = Cont(Box(const_two))
reveal_type(c) # N: Revealed type is "__main__.Cont[builtins.str]"
[builtins fixtures/dataclasses.pyi]

[case testNoCrashOnSelfWithForwardRefGenericDataclass]
from typing import Generic, Sequence, TypeVar, Self
from dataclasses import dataclass

_T = TypeVar('_T', bound="Foo")

@dataclass
class Foo:
foo: int

@dataclass
class Element(Generic[_T]):
elements: Sequence[Self]

@dataclass
class Bar(Foo): ...
e: Element[Bar]
reveal_type(e.elements) # N: Revealed type is "typing.Sequence[__main__.Element[__main__.Bar]]"
[builtins fixtures/dataclasses.pyi]

0 comments on commit 365297c

Please sign in to comment.