Skip to content

Fix crash on inference with recursive alias to recursive instance #14038

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
3 changes: 2 additions & 1 deletion mypy/constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,9 @@ def infer_constraints(template: Type, actual: Type, direction: int) -> list[Cons
for (t, a) in reversed(TypeState.inferring)
):
return []
if has_recursive_types(template):
if has_recursive_types(template) or isinstance(get_proper_type(template), Instance):
# This case requires special care because it may cause infinite recursion.
# Note that we include Instances because the may be recursive as str(Sequence[str]).
if not has_type_vars(template):
# Return early on an empty branch.
return []
Expand Down
6 changes: 6 additions & 0 deletions mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3240,6 +3240,12 @@ def __init__(self) -> None:
def visit_type_var(self, t: TypeVarType) -> bool:
return True

def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:
return True

def visit_param_spec(self, t: ParamSpecType) -> bool:
return True


def has_type_vars(typ: Type) -> bool:
"""Check if a type contains any type variables (recursively)."""
Expand Down
11 changes: 11 additions & 0 deletions test-data/unit/check-recursive-types.test
Original file line number Diff line number Diff line change
Expand Up @@ -826,3 +826,14 @@ z = z
x = y # E: Incompatible types in assignment (expression has type "L", variable has type "K")
z = x # OK
[builtins fixtures/tuple.pyi]

[case testRecursiveInstanceInferenceNoCrash]
from typing import Sequence, TypeVar, Union

class C(Sequence[C]): ...

T = TypeVar("T")
def foo(x: T) -> C: ...

Nested = Union[C, Sequence[Nested]]
x: Nested = foo(42)