Skip to content
Closed
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
13 changes: 13 additions & 0 deletions mypy/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,6 +601,17 @@ def visit_instance(self, left: Instance) -> bool:
type_params = zip(left_args, right_args, right.type.defn.type_vars)
else:
type_params = zip(t.args, right.args, right.type.defn.type_vars)
# With a contravariant type argument the check flips direction, so a class
# whose base refers back to it, like class C(N[N[C]]), can bring us back to
# this same left <: right check. Assume it holds while checking the arguments.
may_cycle = left.type is not right.type and any(
isinstance(tv, TypeVarType)
and tv.variance in (CONTRAVARIANT, VARIANCE_NOT_READY)
for tv in right.type.defn.type_vars
)
assumptions = type_state.get_assumptions(self.proper_subtype)
if may_cycle:
assumptions.append((left, right))
if not self.subtype_context.ignore_type_params:
tried_infer = False
for lefta, righta, tvar in type_params:
Expand All @@ -625,6 +636,8 @@ def visit_instance(self, left: Instance) -> bool:
lefta, righta, COVARIANT, self.proper_subtype, self.subtype_context
):
nominal = False
if may_cycle:
assumptions.pop()
if nominal:
type_state.record_subtype_cache_entry(self._subtype_kind, left, right)
else:
Expand Down
20 changes: 20 additions & 0 deletions test-data/unit/check-generics.test
Original file line number Diff line number Diff line change
Expand Up @@ -3789,3 +3789,23 @@ class C:
# The type variable id below must be small (say under a hundred).
reveal_type(C().meth) # N: Revealed type is "def [S] (x: S`91) -> S`91"
[builtins fixtures/tuple.pyi]

[case testContravariantBaseReferringBackToSubclass]
from typing import Generic, TypeVar

Z = TypeVar("Z", contravariant=True)
X = TypeVar("X")

class N(Generic[Z]): ...

class C(N[N["C"]]): ...

def f(c: C) -> N[C]:
return c

def g(c: C) -> N[int]:
return c # E: Incompatible return value type (got "C", expected "N[int]")

class D(Generic[X], N[N["D[X]"]]): ...

d: N[D[int]] = D[int]()
9 changes: 9 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -2469,3 +2469,12 @@ reveal_type(a[0]) # N: Revealed type is "tuple[builtins.int, builtins.str]"
reveal_type(a[1]) # N: Revealed type is "tuple[builtins.int, builtins.str]"
reveal_type(a[2]) # N: Revealed type is "builtins.tuple[Any, ...]"
[builtins fixtures/tuple.pyi]

[case testPEP695InferredContravariantBaseReferringBackToSubclass]
class N[Z]:
def f(self, x: Z) -> None: ...

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

def f(c: C) -> N[C]:
return c
Loading