When should I make a dataclass immutable?
Quick answer
Use @dataclass(frozen=True) when a record represents a value that should stay fixed after creation, such as a coordinate or measurement. It prevents assigning to or deleting fields, but does not make mutable objects stored in those fields immutable. Choose a regular dataclass when updating fields is part of the record’s intended use. Frozen dataclasses also have a small initialization performance cost. [S1]
The question, the details, the next step.
A practical checklist
Decide whether the record represents a fixed value or an object meant to change.
Use
frozen=Truewhen field reassignment or deletion should be rejected.Check whether fields reference mutable objects; freezing the record does not freeze their contents.
Consider whether the documented small initialization cost matters for your use case.
State whether changes should create a replacement record or update the existing one.
A few more useful answers
What happens if I assign to a field on a frozen dataclass?
The dataclass documentation says assigning to or deleting a field raises FrozenInstanceError. [S1]
Does `frozen=True` make a list field immutable?
No. It restricts changes to the dataclass’s fields, but a referenced mutable object such as a list can still be changed. [S1]
Is there any tradeoff to freezing a dataclass?
The documentation notes a small initialization performance cost. It does not quantify how significant that cost will be in a particular program. [S1]
Sources
References used for this guide.
- [S1] dataclasses — Data Classes (Python 3.15.2 documentation) docs.python.org · Checked
