Sub topic 3
Python Dataclasses: Frozen Instances and Practical Design Choices
Assume you know Python classes, instances, type annotations, and the difference between mutable and immutable objects.
Frozen dataclasses and hashing
frozen=True prevents normal attribute assignment after construction. With the default eq=True, Python also generates a hash when the fields can be hashed. This makes instances suitable as dictionary keys or set members.
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int = 0
v = Version(1, 2)
print(v < Version(2, 0))
print({v: "released"})
try:
v.major = 2
except AttributeError:
print("v is frozen")Frozen does not make nested objects immutable. A frozen dataclass containing a list can still have that list changed, and hashing it may fail. Use immutable field values, such as tuples, when hashability matters.
Converting and copying instances
The dataclasses helpers inspect a dataclass without requiring you to write conversion code.
from dataclasses import dataclass, asdict, astuple, replace, fields
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(asdict(p)) # {'x': 1, 'y': 2}
print(astuple(p)) # (1, 2)
print(replace(p, y=5)) # Point(x=1, y=5)
print([f.name for f in fields(p)]) # ['x', 'y']replace creates a new instance and calls the generated constructor, so validation in __post_init__ runs again.
Inheritance and field ordering
Dataclasses collect base-class fields before subclass fields. If a subclass redefines a field, its original position remains. Therefore, a required field cannot follow an inherited field with a default value. Use a default, kw_only=True, or redesign the fields when this occurs.
`slots=True` and `kw_only`
On Python 3.10 and newer, slots=True stores attributes in __slots__, reducing per-instance memory and preventing arbitrary new attributes. kw_only=True requires callers to name every field.
Choosing another tool
| Tool | Best fit |
|---|---|
| Dataclass | Mutable or frozen records with optional validation and behavior |
| NamedTuple | Small, immutable, tuple-compatible records |
| Plain class | Complex invariants, custom construction, or unusual storage |
| Third-party library | Validation, serialization, or schema features beyond the standard library |
Exercise
Why can a frozen dataclass still be unsafe as a dictionary key?
Show answer
Its nested fields may be mutable or unhashable, even though the dataclass itself blocks attribute assignment.