False positive typing.Self has incompatible type when method uses class' generic type
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
I think this relates to this spec conformance test. As a workaround, async def bar(self: Self, ...) can be used.
If I understand the comment above correctly. mypy is working correctly and this issue should be closed?
The issue is valid, I just wanted to point out the relevant conformance test showing the same issue.
However, a ticket raising the same issue might already exist.