Skip to content

[PEP 695] Fix incorrect Variance Computation with Polymorphic Methods. #19466

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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/subtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-python312.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down