python / python/mypy

Mypy incorrectly infers that parameters are positional-only for `__eq__` methods autogenerated with `@dataclass`

Open
#12,186 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug priority-2-low topic-dataclasses
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

For a class decorated with @dataclass, mypy assumes that the class's __eq__ method will have the exact same signature as object.__eq__. However, this is subtly incorrect. Whereas the signature of object.__eq__ is def __eq__(self, other: object, /) -> bool: ..., the signature of MyDataclass.__eq__ is def __eq__(self, other: object) -> bool: .... I.e., for the method auto-generated by @dataclass, the second argument is positional-or-keyword; whereas the second argument is positional-only for object.__eq__.

Minimal repro (using mypy 0.931, Python 3.10 -- try it on mypy playground here):

from dataclasses import dataclass

@dataclass
class Foo: ...

reveal_type(Foo.__eq__)  # Revealed type is "def (builtins.object, builtins.object) -> builtins.bool"

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 dataclass reproduction and inspect how mypy handles the autogenerated eq method compared with object.eq. Verify the revealed signature, then add coverage showing that the second parameter is positional-or-keyword for dataclass equality methods; done means the incorrect positional-only inference is gone.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.