python / python/mypy

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

Open
#18,279 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the minimal reproducer in main.py or the linked mypy-play example, comparing clonecls() using self.class with clone() using c directly. Run mypy with the reported Python 3.12 setup and add a regression test that captures the expected absence of an argument-type error.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.