[PEP 695] Incorrect Variance Computation with `Self | other` return type
Open
Nobody has claimed this yet.
bug
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
In the example below, FloatScalar is contravariant in FloatT, but mypy thinks it is invariant
from typing import Self
class FloatScalar[FloatT]: # contravariant
def pow(self, arg: FloatT) -> Self | complex: ...
def upcast(arg: FloatScalar[object]) -> FloatScalar[float]:
return arg # ❌️ Incompatible return value type
https://mypy-play.net/?gist=e9e6d34bee57d1c799b71b0f0573175d
If we remove the union in the return type, inference seems to work as expected:
from typing import Self
class FloatScalar[FloatT]: # contravariant
def pow(self, arg: FloatT) -> Self: ...
def upcast(arg: FloatScalar[object]) -> FloatScalar[float]:
return arg # ✅️
https://mypy-play.net/?gist=b0a994e8dda1b85ce2a4cf26631f843e
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the linked mypy-play reproduction and compare the two examples, where adding Self | complex changes the inferred variance of FloatScalar. Trace the variance computation for the PEP 695 generic and add a regression test showing that FloatScalar[object] is accepted as FloatScalar[float] in the union case.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers, devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100