Weird error message for incompatible override when using a `TypeVar` for `self`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
Minimal repro:
from typing import TypeVar
Self = TypeVar("Self")
class Flag:
def __or__(self: Self, other: Self) -> Self: ...
__ror__ = __or__
class IntFlag(int, Flag):
def __or__(self: Self, other: int) -> Self: ...
def __ror__(self: Self, other: int) -> Self: ...
mypy output:
main.py:11: error: Signature of "__ror__" incompatible with supertype "Flag"
main.py:11: note: Superclass:
main.py:11: note: def [Self] __or__(self, Self, Self) -> Self
main.py:11: note: Subclass:
main.py:11: note: def __ror__(self, int) -> IntFlag
Mypy playground link here: https://mypy-play.net/?mypy=latest&python=3.10&gist=26b60881cd02e608bb9e555db4c3f627
Expected Behavior
I'm not sure an error is even appropriate here: no incompatible override is reported for __or__.
Even if an error is appropriate here, however, the error message is weird and garbled. According to the error message, mypy seems to think that __ror__ in the superclass expects three arguments (it only expects two). It also seems to think the method in the subclass will return IntFlag (not necessarily true; the return type will be whatever self is, and self could be any subtype of IntFlag).
The function that creates this error message is here: https://github.com/python/mypy/blob/9b4bce9065cbef6185fbc77f2849b63dc9e5e293/mypy/messages.py#L824
Mypy version used
- 0.950.
- This doesn't seem to be a recent regression: I can reproduce as far back as 0.920, which is the earliest mypy version that has the verbose error messages.
- I've also reproduced the bug on mypy master.
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 minimal Python reproduction and inspect the diagnostic construction in mypy/messages.py around line 824. Compare the reported superclass and subclass signatures with the TypeVar-based self types, then determine whether the override should be accepted or how its message should be rendered. Done means the behavior is corrected and the reproduction is covered by a regression test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100