python / python/mypy

MyPy doesn't seem to know that dataclasses add __eq__

Open
#13,836 2 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

MyPy doesn't seem to understand that dataclasses can generate an __eq__ method. If it's required (such as in an ABC), then it doesn't know that it was created.

To Reproduce

import dataclasses
import abc

@dataclasses.dataclass(eq=False)
class AbstractEq(abc.ABC):
    @abc.abstractmethod
    def __eq__(self, other: object) -> bool:
        pass

@dataclasses.dataclass
class ConcreteEq(AbstractEq):
    x: int

print(ConcreteEq(1) == ConcreteEq(1))

Gist URL: https://gist.github.com/89d988a5c8d37bd10d17445d5e344e63
Playground URL: https://mypy-play.net/?mypy=latest&python=3.10&gist=89d988a5c8d37bd10d17445d5e344e63

Expected Behavior

This should pass. It does at runtime. dataclasses do add __eq__ unless eq=False.

Actual Behavior

main.py:14: error: Cannot instantiate abstract class "ConcreteEq" with abstract attribute "__eq__"
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.981 (playground) and 0.982 (local)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10

I didn't see any other issues that were exactly this issue.

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 running the supplied Python 3.10 reproducer with mypy and inspect how dataclasses and abstract eq are analyzed. Done means the example passes type checking without an abstract-class instantiation error, while preserving the eq=False behavior shown in the issue.

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
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.