mypy icon indicating copy to clipboard operation
mypy copied to clipboard

False positive typing.Self has incompatible type when method uses class' generic type

Open skewty opened this issue 1 year ago • 3 comments

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

skewty avatar Feb 05 '24 06:02 skewty

I think this relates to this spec conformance test. As a workaround, async def bar(self: Self, ...) can be used.

Viicos avatar Feb 05 '24 13:02 Viicos

If I understand the comment above correctly. mypy is working correctly and this issue should be closed?

skewty avatar Feb 21 '24 02:02 skewty

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.

Viicos avatar Feb 21 '24 08:02 Viicos