Skip to content

Commit 365297c

Browse files
authored
Fix crash in Self type on forward reference in upper bound (#14206)
Fixes #14199 This is straightforward, just use the same logic as for regular (user defined) type variables.
1 parent 00ee7d5 commit 365297c

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

mypy/semanal.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1047,7 +1047,11 @@ def setup_self_type(self) -> None:
10471047
assert self.type is not None
10481048
info = self.type
10491049
if info.self_type is not None:
1050-
return
1050+
if has_placeholder(info.self_type.upper_bound):
1051+
# Similar to regular (user defined) type variables.
1052+
self.defer(force_progress=True)
1053+
else:
1054+
return
10511055
info.self_type = TypeVarType("Self", f"{info.fullname}.Self", 0, [], fill_typevars(info))
10521056

10531057
def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:

test-data/unit/check-classes.test

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7679,3 +7679,18 @@ def g(b: Type[Any]) -> None:
76797679

76807680
def h(b: type) -> None:
76817681
class D(b): ...
7682+
7683+
[case testNoCrashOnSelfWithForwardRefGenericClass]
7684+
from typing import Generic, Sequence, TypeVar, Self
7685+
7686+
_T = TypeVar('_T', bound="Foo")
7687+
7688+
class Foo:
7689+
foo: int
7690+
7691+
class Element(Generic[_T]):
7692+
elements: Sequence[Self]
7693+
7694+
class Bar(Foo): ...
7695+
e: Element[Bar]
7696+
reveal_type(e.elements) # N: Revealed type is "typing.Sequence[__main__.Element[__main__.Bar]]"

test-data/unit/check-dataclasses.test

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1981,3 +1981,23 @@ def const_two(x: T) -> str:
19811981
c = Cont(Box(const_two))
19821982
reveal_type(c) # N: Revealed type is "__main__.Cont[builtins.str]"
19831983
[builtins fixtures/dataclasses.pyi]
1984+
1985+
[case testNoCrashOnSelfWithForwardRefGenericDataclass]
1986+
from typing import Generic, Sequence, TypeVar, Self
1987+
from dataclasses import dataclass
1988+
1989+
_T = TypeVar('_T', bound="Foo")
1990+
1991+
@dataclass
1992+
class Foo:
1993+
foo: int
1994+
1995+
@dataclass
1996+
class Element(Generic[_T]):
1997+
elements: Sequence[Self]
1998+
1999+
@dataclass
2000+
class Bar(Foo): ...
2001+
e: Element[Bar]
2002+
reveal_type(e.elements) # N: Revealed type is "typing.Sequence[__main__.Element[__main__.Bar]]"
2003+
[builtins fixtures/dataclasses.pyi]

0 commit comments

Comments
 (0)