How do you make a dataclass immutable (read-only after creation) using frozen=True?
Short answer
Pass frozen=True to the @dataclass decorator to make every field effectively read-only after __init__ runs — attempting to assign to any field afterward raises a FrozenInstanceError, and frozen dataclasses also automatically become hashable (if eq=True, the default), letting…
Advertisement
AModel answer
Pass frozen=True to the @dataclass decorator to make every field effectively read-only after __init__ runs — attempting to assign to any field afterward raises a FrozenInstanceError, and frozen dataclasses also automatically become hashable (if eq=True, the default), letting them be used as dict keys or set elements.
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
# p.x = 99 # dataclasses.FrozenInstanceError: cannot assign to field 'x'
points_set = {Point(1, 2), Point(3, 4)} # works: frozen dataclasses are hashableReal-world example
Creating an immutable value object (like a Point or Money amount) that's also safely usable as a dictionary key or set element.
Likely follow-ups
- Does frozen=True prevent mutation of a MUTABLE object stored INSIDE one of the dataclass's fields, like a list attribute?
Related topics