Sub topic 9
Frozen dataclasses and hashing
This chapter assumes you know @dataclass, field(), __post_init__, and the difference between mutable and immutable objects. Here you will see how frozen=True blocks changes, and how it decides whether instances can be dict keys or set members.
Why a plain dataclass is not hashable
A hashable object has a __hash__ method that returns an integer. That integer must stay the same for the object's lifetime, because dicts and sets use it to find entries. Python also requires that equal objects have equal hashes.
By default @dataclass generates __eq__. Equality now depends on field values, which can change. So Python sets __hash__ to None, and the instances become unhashable.
from dataclasses import dataclass
@dataclass
class Tag:
name: str
try:
{Tag("a")}
except TypeError as e:
print(e) # unhashable type: 'Tag'Freezing an instance
With frozen=True, the decorator generates __setattr__ and __delattr__ methods that raise FrozenInstanceError. Fields can no longer be assigned or deleted after __init__ finishes. Because the fields cannot change, a hash built from them is safe, so the decorator generates __hash__ too.
from dataclasses import dataclass, field, replace, FrozenInstanceError
@dataclass(frozen=True)
class Money:
amount: int
currency: str = "EUR"
label: str = field(default="", compare=False)
a = Money(5, label="lunch")
b = Money(5, label="coffee")
print(a == b) # True
print(hash(a) == hash(b)) # True
print({a: "paid"}[b]) # paid
try:
a.amount = 10
except FrozenInstanceError:
print("cannot modify a frozen instance")
print(replace(a, amount=10)) # Money(amount=10, currency='EUR', label='lunch')The label field has compare=False. It is left out of __eq__ and, because hash=None follows compare, out of __hash__ as well. This keeps the rule that equal objects have equal hashes. To change a frozen instance, build a modified copy with replace().
What eq and frozen decide together
The decorator picks __hash__ from the eq and frozen flags.
| eq | frozen | Resulting `__hash__` |
|---|---|---|
| True (default) | False (default) | Set to `None`, unhashable |
| True | True | Generated from the compared fields |
| False | either | Inherited from the base class, usually identity-based |
There is also unsafe_hash=True. It generates __hash__ even when the class is mutable. Use it only when you can guarantee that no instance changes while it is inside a set or dict.
Common errors
Frozen is shallow
frozen=True stops you from rebinding a field. It does not freeze the object that the field refers to. A list inside a frozen instance can still be changed, and the instance then cannot be hashed.
from dataclasses import dataclass
@dataclass(frozen=True)
class Bag:
items: list[str]
bag = Bag(["a"])
bag.items.append("b")
print(bag) # Bag(items=['a', 'b'])
try:
hash(bag)
except TypeError as e:
print(e) # unhashable type: 'list'Use tuples or frozensets for fields in a hashable dataclass.
Setting derived fields in `__post_init__`
Plain assignment in __post_init__ fails on a frozen class, because it goes through the blocked __setattr__. Call object.__setattr__ instead.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Celsius:
degrees: float
kelvin: float = field(init=False)
def __post_init__(self):
object.__setattr__(self, "kelvin", self.degrees + 273.15)
print(Celsius(0)) # Celsius(degrees=0, kelvin=273.15)Mixing frozen and non-frozen in inheritance
A frozen dataclass cannot inherit from a non-frozen one, and a non-frozen one cannot inherit from a frozen one. Python raises TypeError when the class is defined. Make the whole hierarchy frozen or none of it.
Exercise
Exercise
A dataclass is declared as @dataclass(frozen=True) with a field tags: list[str]. Creating an instance works, but {instance} raises TypeError. Why does this happen, and how would you fix it?
Show answer
The generated __hash__ hashes a tuple of the field values, and a list is unhashable, so hashing the instance fails. Creating the instance works because frozen=True only blocks reassignment of fields. Change the field to tuple[str, ...] or frozenset[str]. Alternatively, set compare=False on the field to leave it out of the hash and equality.