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

from dataclasses import dataclass

@dataclass(frozen=True)
class Coord:
    x: int
    y: int

c = Coord(3, 4)
print(c)        # Coord(x=3, y=4)

try:
    c.x = 99    # frozen instances reject attribute assignment
except Exception as exc:
    print(type(exc).__name__, ':', exc)
# FrozenInstanceError: cannot assign to field 'x'

# Hashable for free, so they work as dict keys and set members.
seen = {Coord(0, 0), Coord(1, 0), Coord(0, 0)}
print(seen)               # {Coord(x=0, y=0), Coord(x=1, y=0)}
print(len(seen))          # 2

weights = {Coord(0, 0): 1.0, Coord(1, 0): 2.5}
print(weights[Coord(0, 0)])  # 1.0

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.