Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Frozen Dataclasses in Python: Making Data Immutable

Learn how frozen dataclasses work in Python. This article covers frozen=True syntax, shallow immutability, hashability, replace(), slots, and when to use them.

~4 min readPython
#dataclasses#immutability#Python#object-oriented programming
A stylized padlock integrated with a Python code snippet, representing immutable frozen dataclasses.

In Python, @dataclass can create immutable objects by setting frozen=True. A frozen dataclass raises FrozenInstanceError if you try to assign to or delete one of its fields after the instance is created. This makes frozen dataclasses useful for value objects, configuration records, and data that should stay constant across function calls or threads.

What frozen=True Actually Does

A frozen dataclass is not a separate type; it is a regular dataclass with generated __setattr__ and __delattr__ methods. These methods protect the fields declared on the class:

python
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: float y: float

With this class, p.x = 3 raises FrozenInstanceError, and del p.x raises the same error. During __init__, the generated code uses object.__setattr__ to set the initial field values, so construction still works.

This immutability is shallow. If a field contains a mutable object, such as a list or dictionary, the reference to that object is protected, but the object itself can still be modified. For deeper immutability, use immutable field types such as tuple or frozenset, or rely on a library that provides recursive immutability.

Creating a Frozen Dataclass

The syntax is minimal: add frozen=True to the decorator and define fields as usual.

python
from dataclasses import dataclass, FrozenInstanceError @dataclass(frozen=True) class User: id: int name: str email: str u = User(id=1, name='Alice', email='alice@example.com') print(u.name) # Alice try: u.name = 'Bob' except FrozenInstanceError: print('Cannot modify frozen instance')

FrozenInstanceError is a subclass of AttributeError, so code that catches AttributeError will also handle this case.

Why Use a Frozen Dataclass?

Frozen dataclasses simplify reasoning about state because fields cannot be reassigned after creation. This is useful for:

  • Configuration values that are loaded once and must not change during runtime.
  • Value objects in domain-driven design, where equality is based on field values rather than identity.
  • Dictionary keys or set members, because frozen dataclasses are hashable when all fields are hashable.

Frozen dataclasses are convenient for passing value objects across threads when the fields themselves are immutable: no thread can replace a field, so the value remains stable. If a field contains a mutable object, that inner object still needs synchronization.

Hashability and Equality

By default, dataclasses define __eq__ but not __hash__, so regular dataclasses are unhashable. With frozen=True and the default eq=True, the generated class sets __hash__ based on the tuple of field values. If you set eq=False, __hash__ is left untouched and is not generated by the dataclass. As long as every field is hashable, instances can be used as dictionary keys or set members:

python
@dataclass(frozen=True) class Coordinate: lat: float lon: float locations = {Coordinate(40.7, -74.0): 'NYC'} print(locations[Coordinate(40.7, -74.0)]) # NYC

If a field is unhashable, such as a list, the generated hash will fail at runtime. If you override __hash__ manually, base it on immutable aspects of the object; otherwise hash lookups can become inconsistent after nested state changes.

Modifying a Frozen Dataclass: dataclasses.replace

Frozen does not mean you can never create a changed version. dataclasses.replace creates a new instance with selected fields replaced, leaving the original untouched:

python
from dataclasses import replace original = User(id=1, name='Alice', email='alice@example.com') updated = replace(original, email='alice@newdomain.com') print(original.email) # alice@example.com print(updated.email) # alice@newdomain.com

replace copies field values and then applies the requested changes. It works with any dataclass, but it is especially useful for frozen ones because direct assignment is not possible.

Practical Performance Details

Frozen dataclasses add generated __setattr__ and __delattr__ methods that guard field assignment and deletion. Attribute reads go through normal attribute lookup. The generated __hash__ creates a tuple of field values and hashes it each time hash() is called; the object does not cache that result. If you use frozen instances repeatedly as dictionary keys in a performance-sensitive path, keep this in mind.

If you are on Python 3.10 or later, you can combine frozen=True with slots=True to create slotted classes that do not have a __dict__:

python
@dataclass(frozen=True, slots=True) class Config: host: str port: int

The immutability behavior is the same.

When a Frozen Dataclass Is Not Enough

Frozen dataclasses protect fields, not the contents of nested mutable objects:

python
@dataclass(frozen=True) class Order: items: list order = Order(items=['apple', 'banana']) order.items.append('cherry') # This works!

The items list is mutable, so order.items.append('cherry') succeeds even though order is frozen. To make this field immutable, store a tuple instead:

python
@dataclass(frozen=True) class Order: items: tuple

Then order.items cannot be modified. For more deeply nested data, you may need recursive conversion or a library designed for persistent immutable collections.

Frozen dataclasses also do not prevent methods you define from mutating mutable fields. If a method calls self.items.append(...), the dataclass will not stop it. Design the class so that methods do not mutate internal state if immutability is a contract you want to rely on.

Compatibility and Version Notes

Dataclasses were introduced in Python 3.7, and frozen=True has been available since that version. In Python 3.10 and later, slots=True is supported as a separate dataclass option and can be combined with frozen=True. For Python 3.6, use the dataclasses backport package; its frozen parameter behaves the same way, but check that the backport is compatible with your tooling.

Choosing Between Frozen and Regular Dataclasses

Use a regular dataclass when the object represents a mutable entity that changes over time, such as a user session or shopping cart. Use a frozen dataclass when the object is a value that should stay constant, such as a point in a graph or a parsed configuration record.

A practical rule is to start with frozen=True unless you have a specific reason to mutate the object. When a changed value is needed, replace creates a new instance. That pattern makes state changes explicit and reduces accidental modifications in shared code.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.