python / python/mypy

False positive for class method without Self annotation

Open
#15,771 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Mypy reports an error for method save1 (without annotation) but no errors for save2 and save3 (with different Self annotations), despite their (almost) identical function bodies:

from copy import deepcopy
from typing import Self

class A:
    states: list[Self]

    def save1(self) -> None:
        self.states.append(deepcopy(self))  # error: Argument 1 to "append" of "list" has incompatible type "A"; expected "Self"  [arg-type]

    def save2(self: Self) -> None:
        self.states.append(deepcopy(self))

    def save3(self) -> Self:
        self.states.append(deepcopy(self))
        return self

This bug might be related to #15529 but is not fixed by #15541.

### Tasks

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 by reproducing the reported diagnostic with the Python example in the issue, comparing save1, save2, and save3. Review related issues #15529 and #15541, then trace the Self-annotation handling that produces the inconsistent result. Done means the equivalent methods receive consistent, correct diagnostics and the regression is covered by a test.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.