diff --git a/mypy/subtypes.py b/mypy/subtypes.py index ca21e67f3a6e5..377b99fa19d46 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -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: @@ -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: diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test index 1570249c0dab1..32051b3816fd1 100644 --- a/test-data/unit/check-generics.test +++ b/test-data/unit/check-generics.test @@ -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]() diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index b756da6ea9b30..ebd4ec43febd2 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -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