Sub topic 9
Frozen dataclasses and hashing
This chapter covers frozen=True, which makes instances read-only. It also covers how eq, frozen and unsafe_hash together decide whether a dataclass can be a dictionary key or a set member.
It assumes you know the following:
- Basic
@dataclassusage andfield(). - What
__eq__and__hash__are. - The difference between mutable and immutable objects.
order=True, which is covered in the previous chapter.
Why hashing is a dataclass question
Python's hash rule has two parts. If two objects compare equal, they must have the same hash. And an object's hash must not change while it sits in a set or is used as a dict key.
A class with mutable fields cannot honestly promise the second part. Dataclasses therefore make a decision for you based on two flags, eq and frozen. The default eq=True generates __eq__, and the generated __eq__ makes the default dataclass unhashable.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(Point.__hash__) # None
try:
{p: "a"}
except TypeError as e:
print(e) # unhashable type: 'Point'The decorator sets __hash__ to None here. This is deliberate. Because Point is mutable and compares by value, a hash based on x and y could change after the object is stored in a set.
What frozen=True does
frozen=True adds __setattr__ and __delattr__ methods that always raise FrozenInstanceError. That exception is a subclass of AttributeError.
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int = 0
patch: int = 0
print(Version(1, 2) < Version(1, 10)) # True
print({Version(1, 0): "first"}) # usable as a dict key
v = Version(1, 0, 0)
try:
v.major = 2
except FrozenInstanceError:
print("cannot modify a frozen instance")With eq=True and frozen=True, the decorator also generates a __hash__. It hashes a tuple of the field values, so hash(Version(1, 0, 0)) behaves like hash((1, 0, 0)). Equal instances always get equal hashes.
Frozen instances are the usual choice for:
- Dictionary keys and set members.
- Cache keys.
- Value objects such as coordinates, money amounts and configuration records.
- Data shared between threads, where nobody can change it unexpectedly.
Making a changed copy
A frozen instance cannot be edited, so you build a new one. dataclasses.replace copies the instance and overrides the fields you name.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Version:
major: int
minor: int = 0
patch: int = 0
v1 = Version(1, 4, 2)
v2 = replace(v1, minor=5, patch=0)
print(v1) # Version(major=1, minor=4, patch=2)
print(v2) # Version(major=1, minor=5, patch=0)replace calls the constructor again, so __post_init__ runs on the new object. Validation therefore applies to every copy.
The hash decision table
The decorator looks at eq, frozen and unsafe_hash and picks one of these actions. The table assumes you have not written your own __hash__ in the class body.
| eq | frozen | unsafe_hash | Result for `__hash__` |
|---|---|---|---|
| True | False | False | Set to `None`. Instances are unhashable. |
| True | True | False | Generated from the fields. Instances are hashable. |
| False | either | False | Inherited from the base class, normally `object`'s identity hash. |
| any | any | True | Generated from the fields, whatever `frozen` is. |
The next diagram shows the same decision as a path.
If you write __hash__ yourself in the class body, the rules change in two ways. With eq=True and frozen=False, the decorator leaves your method alone instead of setting it to None. With unsafe_hash=True, the decorator raises TypeError because it cannot tell which hash you want.
Choosing which fields take part in the hash
The generated hash uses the same fields as __eq__. Each field has two options that control this:
compare=Falseremoves the field from__eq__,ordercomparisons and the hash.hash=Falseremoves the field only from the hash. The default,hash=None, means "followcompare".
Keeping the two consistent matters. If a == b is true, hash(a) == hash(b) must be true. Removing a field from the hash while it still takes part in equality is legal, because equal objects still hash equally. Removing it from equality while it stays in the hash is not legal, because two equal objects could then hash differently.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Document:
id: int
title: str = field(compare=False)
a = Document(1, "Draft")
b = Document(1, "Final")
print(a == b) # True
print(hash(a) == hash(b)) # True
print(len({a, b})) # 1Here title is metadata. Two documents with the same id count as the same document.
Setting fields inside __post_init__
The frozen __setattr__ also blocks assignments in __post_init__, so a derived field cannot be set the usual way. The standard workaround is object.__setattr__, which skips the class's own __setattr__.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width < 0 or self.height < 0:
raise ValueError("width and height must be non-negative")
object.__setattr__(self, "area", self.width * self.height)
print(Rectangle(3, 4)) # Rectangle(width=3, height=4, area=12)This is the only place where object.__setattr__ is normal practice. The same call works anywhere, so a frozen class guards against accidents, not against deliberate bypassing.
Frozen is shallow
frozen=True only blocks assigning to the instance's own attributes. If a field holds a mutable object, you can still change that object.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Team:
name: str
members: list[str] = field(default_factory=list)
t = Team("core")
t.members.append("ana")
print(t) # Team(name='core', members=['ana'])
try:
hash(t)
except TypeError as e:
print(e) # unhashable type: 'list'Two things go wrong here:
- The instance changed even though it is "frozen".
hash(t)fails, because the generated hash must hash every field and a list is unhashable. The class looks hashable, but the failure only appears when you callhash().
The fix is to use immutable field types, such as tuple[str, ...] instead of list[str], frozenset instead of set, and nested frozen dataclasses instead of dicts.
from dataclasses import dataclass
@dataclass(frozen=True)
class Team:
name: str
members: tuple[str, ...] = ()
t = Team("core", ("ana", "ben"))
print(hash(t) == hash(Team("core", ("ana", "ben")))) # TrueThe tuple default () is immutable, so you do not need default_factory here.
unsafe_hash=True
unsafe_hash=True generates __hash__ even for a mutable class. The name is a warning. If you change a field after the object has been stored in a set or dict, its hash changes and the container can no longer find it.
from dataclasses import dataclass
@dataclass(unsafe_hash=True)
class Tag:
name: str
t = Tag("a")
seen = {t}
t.name = "b"
print(t in seen) # False
print(Tag("a") in seen) # False
print(len(seen)) # 1The set still holds one object, but both lookups fail. The stored hash belongs to the old value "a". The lookup for t hashes the new value "b" and looks in the wrong place. The lookup for Tag("a") finds the right place, but the stored object now holds "b", so equality fails.
Use unsafe_hash=True only when you can guarantee that instances are not modified while they are in a hashed container. In most cases frozen=True is the better choice, because the class enforces that guarantee for you.
Inheritance and frozen
A frozen dataclass and a non-frozen one cannot be mixed in an inheritance chain. A non-frozen dataclass cannot inherit from a frozen one, and a frozen dataclass cannot inherit from a non-frozen one. Either case raises TypeError when the class is defined. A plain class with no dataclass fields can still appear as a base.
from dataclasses import dataclass
@dataclass(frozen=True)
class Base:
x: int
try:
@dataclass
class Child(Base):
y: int = 0
except TypeError as e:
print("TypeError:", e)Make every dataclass in a hierarchy frozen, or none of them.
Costs and limits
- A frozen dataclass's generated
__init__assigns fields throughobject.__setattr__, which is slightly slower than normal assignment. For most programs the difference does not matter. - Frozen does not make a class thread-safe by itself. It only removes one source of shared mutable state.
eq=Truecompares only instances of the same class. AVersionand a subclass ofVersioncompare as not equal, even with identical field values.- A hash is not stable across processes for
strandbytesfields, because of hash randomization. Never store a Python hash in a file or database and compare it later.
Quick guidance
- Need dict keys, set members or safe sharing? Use
frozen=True. - Need to "edit" a frozen object? Use
dataclasses.replace. - Have mutable fields in a frozen class? Swap them for immutable types.
- Need only some fields to define identity? Use
compare=Falseorhash=Falseon the others. - Think you need
unsafe_hash=True? Check first whetherfrozen=Trueworks.
Exercise
Given @dataclass class Item: sku: str; qty: int, does {Item("a", 1)} work? What single change to the decorator makes it work, and what does that change also forbid?
Show answer
It raises TypeError: unhashable type: 'Item', because eq=True with frozen=False sets __hash__ to None. Writing @dataclass(frozen=True) makes the class hashable by generating a hash from its fields. It also forbids assigning to sku or qty after creation, which raises FrozenInstanceError.
Exercise
A frozen dataclass Job has fields id: int and log: list[str]. Instantiating works, but hash(job) fails. Why, and how do you fix it without changing what id means?
Show answer
The generated hash covers every field that takes part in comparison, and a list is unhashable. Either change log to tuple[str, ...], or exclude it from comparison and hashing with field(compare=False). The second option also means two jobs with the same id compare equal even when their logs differ.
Exercise
Why does a frozen dataclass need object.__setattr__(self, "area", ...) in __post_init__ to set a computed field, and why can't you write self.area = ...?
Show answer
frozen=True replaces __setattr__ with a method that always raises FrozenInstanceError. __post_init__ runs after __init__ as an ordinary method, so self.area = ... hits that blocking method. object.__setattr__ calls the base implementation directly and skips the block.