python / python/mypy

Incorrect inference for types with `__eq__` and no `__hash__`

Open
#18,622 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

problem

class A:
    def __eq__(self, o: object, /) -> bool:
        return self is o

reveal_type(A().__hash__)  # def () -> builtins.int

https://mypy-play.net/?mypy=latest&python=3.13&flags=strict%2Clocal-partial-types&gist=2b23624b1df772175b70c08e36a6e912

yet

>>> class A:
...     def __eq__(self, o: object, /) -> bool:
...         return self is o
...         
>>> type(A.__hash__)
<class 'NoneType'>

solution

iff. class A, and only class A (i.e. excluding any base classes)

  • implements __eq__, and
  • does not implement __hash__

infer A.__hash__: ClassVar[None]

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

No source file or test is named. Reproduce the example from the mypy-play link, then locate the type inference entry point for eq and hash. Done means a class defining eq without its own hash is inferred with hash: ClassVar[None], without using base-class definitions.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
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.