Python Snippet

Frozen + slots Dataclasses

Difficulty: Medium

`@dataclass(frozen=True)` makes instances immutable and hashable, which lets you use them as dict keys or set members. `slots=True` (3.10+) skips the `__dict__` allocation, saving roughly 40% of memory per instance and making attribute access slightly faster. This entry covers each flag separately and shows when combining them is the right call.

Code Snippets
/

Frozen + slots Dataclasses

Frozen + slots Dataclasses

`@dataclass(frozen=True)` makes instances immutable and hashable, which lets you use them as dict keys or set members. `slots=True` (3.10+) skips the `__dict__` allocation, saving roughly 40% of memory per instance and making attribute access slightly faster. This entry covers each flag separately and shows when combining them is the right call.

Python
Medium
3 snippets
py-dataclasses
py-slots
py-type-hints
py-standard-library

591 views

13

frozen=True overrides __setattr__ to raise FrozenInstanceError on every assignment after construction. As a side effect Python also synthesizes __hash__ (mutable dataclasses are unhashable by default), which makes the instance usable as a dict key, a set member, or an lru_cache argument. Use frozen for value objects like coordinates, ranges, money amounts: anything where two instances with the same fields should be the same logical thing. The cost is dataclasses.replace(c, x=99) instead of c.x = 99 for updates.