False positive typing.Self has incompatible type when method uses class' generic type
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Bug Report
mypy seems to get confused about type of typing.Self, when class is also typing.Generic, inside methods if a parameter has
the same type as the class Generic's TypeVar.
To Reproduce
from collections.abc import Awaitable, Callable
from typing import Generic, Self, TypeVar
AttributeValueT = TypeVar("AttributeValueT")
class Attribute(Generic[AttributeValueT]):
def __init__(self, on_changed: Callable[[Self], Awaitable[None]]) -> None:
self._on_changed = on_changed
async def bar(self, _: AttributeValueT) -> None:
# Argument 1 has incompatible type "Attribute[AttributeValueT]"; expected "Self" [arg-type]
await self._on_changed(self) # type: ignore[arg-type]
Expected Behavior
I expect self / Self to have the correct type and to be able to avoid # type: ignore[arg-type]
Actual Behavior
See mypy error is in method comment above; error only makes sense with code as context.
Your Environment
- Mypy version used: mypy 1.8.0 (compiled: yes)
- Python version used: 3.11.7
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 by running the provided reproducer with mypy 1.8.0 and confirm the incompatible-type error involving typing.Self and the generic AttributeValueT. Trace the Self handling for methods on Generic classes, then add a regression test showing that self is accepted without a type ignore and that the test suite passes.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 42/100