Skip to content

Commit fa22a49

Browse files
authored
Fix crash on inference with recursive alias to recursive instance (#14038)
Fixes #14031 It turns out premature optimization is the root of all evil. (It turns out this costs us less than 1% time on self-check).
1 parent 7465abd commit fa22a49

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

mypy/constraints.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -177,8 +177,9 @@ def infer_constraints(template: Type, actual: Type, direction: int) -> list[Cons
177177
for (t, a) in reversed(TypeState.inferring)
178178
):
179179
return []
180-
if has_recursive_types(template):
180+
if has_recursive_types(template) or isinstance(get_proper_type(template), Instance):
181181
# This case requires special care because it may cause infinite recursion.
182+
# Note that we include Instances because the may be recursive as str(Sequence[str]).
182183
if not has_type_vars(template):
183184
# Return early on an empty branch.
184185
return []

mypy/types.py

+6
Original file line numberDiff line numberDiff line change
@@ -3240,6 +3240,12 @@ def __init__(self) -> None:
32403240
def visit_type_var(self, t: TypeVarType) -> bool:
32413241
return True
32423242

3243+
def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:
3244+
return True
3245+
3246+
def visit_param_spec(self, t: ParamSpecType) -> bool:
3247+
return True
3248+
32433249

32443250
def has_type_vars(typ: Type) -> bool:
32453251
"""Check if a type contains any type variables (recursively)."""

test-data/unit/check-recursive-types.test

+11
Original file line numberDiff line numberDiff line change
@@ -826,3 +826,14 @@ z = z
826826
x = y # E: Incompatible types in assignment (expression has type "L", variable has type "K")
827827
z = x # OK
828828
[builtins fixtures/tuple.pyi]
829+
830+
[case testRecursiveInstanceInferenceNoCrash]
831+
from typing import Sequence, TypeVar, Union
832+
833+
class C(Sequence[C]): ...
834+
835+
T = TypeVar("T")
836+
def foo(x: T) -> C: ...
837+
838+
Nested = Union[C, Sequence[Nested]]
839+
x: Nested = foo(42)

0 commit comments

Comments
 (0)