Skip to content

Python: FrozenInstanceError – cannot assign to field (frozen dataclass)

Python & Gotested on Python 3.14.2, uv 0.9.26

Assigning to a field of a dataclass object fails. The class is defined with @dataclass(frozen=True): objects are immutable after creation and hashable in return.

Symptom

try:
    e.status = 500
except AttributeError as err:
    print(type(err).__name__, err)
FrozenInstanceError cannot assign to field 'status'

FrozenInstanceError is a subclass of AttributeError – that is why except AttributeError catches it.

Diagnosis

Look for frozen=True in the class definition.

@dataclass(frozen=True, slots=True)
class LogEntry:
    ip: str

Causes

frozen=TrueThe dataclass is immutable

frozen=True makes entries immutable and hashable, slots=True saves memory per object – noticeable with millions of log lines.

Fix

Do not change values afterwards; set them correctly at creation or create a new object with the changed value. If you really need mutable objects, leave out frozen=True.

Don't: Remove frozen=True just to make one assignment work. You lose hashability and the protection against accidental changes.

▶
Break it yourself and find it – free
Python hands-on, Day 2: functions, dataclasses and modules with the logsum tool.
Go to day 2 →

FAQ

Does except AttributeError catch it?

Yes. FrozenInstanceError inherits from AttributeError; the course catches it exactly like that.

Why use frozen at all?

Immutable entries cannot be overwritten by accident and can be used as keys in sets and dicts.

Related error patterns

More