Separate Frozen Fields from Slots
Core idea
frozen=True prevents ordinary field assignment and deletion; it is not deep immutability. slots=True (Python 3.10+) creates a slotted class with declared storage and, in a simple standalone class, no instance dict. The options address different problems and may be combined. Hashability also depends on the fields and equality settings.
from dataclasses import dataclass,FrozenInstanceError@dataclass(frozen=True)class Batch: labels:list[str]b=Batch(['A'])b.labels.append('B')try: b.labels=[]except FrozenInstanceError: print('blocked')print(b.labels)Rebinding the field is blocked, but the list inside it remains mutable.
Use slots without freezing
from dataclasses import dataclass@dataclass(slots=True)class Reading: value:intr=Reading(4);r.value=5print(r.value,hasattr(r,'__dict__'))try: r.extra=1except AttributeError: print('no extra field')A declared field is writable, but this standalone slotted instance does not allow arbitrary new attributes.
Common mistake
Do not assume every frozen record is hashable: a generated hash can fail on an unhashable field. Inherited classes can also affect slots and dict availability.
Practice
Create a frozen slotted record containing a tuple of integers. Test equality, hashing and attempts to reassign a field; compare with a list-valued record.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Frozen and slotted dataclasses
Check your understanding of frozen and slotted dataclasses.
What is printed?
from dataclasses import dataclass@dataclass(slots=True)class A: n:inta=A(1);a.n=2print(a.n)What is printed?
from dataclasses import dataclass@dataclass(frozen=True)class A: xs:lista=A([]);a.xs.append(1)print(a.xs)Which option restricts normal field rebinding?
Can a frozen record contain a mutable list?