python / python/mypy

`@dataclass` does not handle `__hash__: None` special case

Open
#11,495 0 comments 1 reaction 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

While working on https://github.com/python/mypy/issues/11463 I found that adding __hash__: None annotations does not work correctly.

Mypy says:

from dataclasses import dataclass

@dataclass(unsafe_hash=False, eq=True, frozen=False)
class SecondCase2:
    x: int
    __hash__: None  # E: Incompatible types in assignment (expression has type "None", base class "object" defined the type as "Callable[[object], int]")
print(SecondCase2(1).__hash__)  # N: Revealed type is "None" \
                                                      # E: Missing positional argument "__hash__" in call to "SecondCase2"

It looks like __hash__ is added to fields and __init__. While runtime version works just fine:

» python out/ex.py
SecondCase2(x=1, __hash__=<slot wrapper '__hash__' of 'object' objects>)

I will fix it in the same PR as https://github.com/python/mypy/issues/11463

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 provided dataclass reproducer and compare mypy's diagnostics with the shown runtime behavior. Trace how dataclass fields and init handle hash: None, then add coverage confirming it is not treated as a field or constructor argument; check the related issue #11463 first because the report says this fix will land in the same PR.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.