diff --git a/mypy/subtypes.py b/mypy/subtypes.py index 1aa8543505ec..2b3922ed79a8 100644 --- a/mypy/subtypes.py +++ b/mypy/subtypes.py @@ -2212,7 +2212,8 @@ def infer_variance(info: TypeInfo, i: int) -> bool: settable = False # TODO: handle settable properties with setter type different from getter. - typ = find_member(member, self_type, self_type) + plain_self = fill_typevars_with_any(info) # self-type without type variables + typ = find_member(member, self_type, plain_self) if typ: # It's okay for a method in a generic class with a contravariant type # variable to return a generic instance of the class, if it doesn't involve diff --git a/test-data/unit/check-python312.test b/test-data/unit/check-python312.test index bfd6334b5077..7da91a930b0c 100644 --- a/test-data/unit/check-python312.test +++ b/test-data/unit/check-python312.test @@ -450,6 +450,21 @@ class Contra2[T]: d1: Contra2[int] = Contra2[float]() d2: Contra2[float] = Contra2[int]() # E: Incompatible types in assignment (expression has type "Contra2[int]", variable has type "Contra2[float]") +[case testPEP695InferVariancePolymorphicMethod] +class Cov[T]: + def get(self) -> T: ... + def new[S](self: "Cov[S]", arg: list[S]) -> "Cov[S]": ... + +cov_pos: Cov[object] = Cov[int]() +cov_neg: Cov[int] = Cov[object]() # E: Incompatible types in assignment (expression has type "Cov[object]", variable has type "Cov[int]") + +class Contra[T]: + def set(self, arg: T) -> None: ... + def new[S](self: "Contra[S]", arg: list[S]) -> "Contra[S]": ... + +contra_pos: Contra[object] = Contra[int]() # E: Incompatible types in assignment (expression has type "Contra[int]", variable has type "Contra[object]") +contra_neg: Contra[int] = Contra[object]() + [case testPEP695InheritInvariant] class Invariant[T]: x: T