python/mypy

`self.__class__` produces a type check with a constructor where a concrete reference to the class works fine

Opened this issue · 1 comments

glyph commented

Bug Report

I'm not sure how this bug generalizes, but I discovered this with an HTTP headers abstraction with a clone method and the example minifies pretty far down, as shown below

To Reproduce

from typing import Mapping, Sequence, AnyStr, Self

class c:
    _v: dict[bytes, list[bytes]]
    def __init__(self, v: Mapping[AnyStr, Sequence[AnyStr]]):
        pass

    def clonecls(self) -> Self:
        return self.__class__(self._v)

    def clone(self) -> c:
        return c(self._v)

https://mypy-play.net/?mypy=latest&python=3.12&gist=0be4308fb57a3685fafab2ac51a97c85

Expected Behavior

No errors.

Actual Behavior

main.py:9: error: Argument 1 to "c" has incompatible type "dict[bytes, list[bytes]]"; expected "Mapping[AnyStr, Sequence[AnyStr]]"  [arg-type]

Your Environment

  • Mypy version used: 1.13.0
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12

Thanks for the report!

Simplified reproducer:

from typing import TypeVar

T = TypeVar("T")

class Foo:
    def __init__(self, x: T) -> None: ...

bar: type[Foo]
bar(123)  # E: Argument 1 to "Foo" has incompatible type "int"; expected "T"  [arg-type]