dataclasses_hash error

Non-hashable dataclass assigned to a Hashable-annotated variable

A @dataclass with eq=True (the default) sets __hash__ to None unless the class is frozen=True, uses unsafe_hash=True, or explicitly defines a __hash__ method. Assigning such an instance to a variable annotated Hashable is a type error.

from dataclasses import dataclass
from typing import Hashable

@dataclass
class DC1:
    a: int

v: Hashable = DC1(0)  # E — DC1.__hash__ is None

@dataclass(eq=True, frozen=True)
class DC2:
    a: int

v2: Hashable = DC2(0)  # OK — frozen dataclasses are hashable

PEP 557 specifies the __hash__ synthesis rules: - If eq is true and frozen is false, __hash__ is set to None. - If eq is true and frozen is true, Python synthesises a __hash__. - If unsafe_hash is true, Python synthesises a __hash__ regardless. - If eq is false, __hash__ is left untouched (inherited from parent). - If the class defines __hash__ explicitly, that definition is used.

How to handle it

Every rule is on by default — strict is the default, not a cage. You can dial dataclasses_hash down per-file or per-path from your editor or pyproject.toml, or fix the code so it type-checks. See the Type System rules and the complete diagnostic reference.

Canonical URL: https://www.basilisk-python.dev/errors/dataclasses_hash