How to Use Frozen Dataclass in Python: Syntax and Examples
Use
@dataclass(frozen=True) to create an immutable dataclass in Python. This makes instances read-only, so their fields cannot be changed after creation.Syntax
The @dataclass decorator creates classes with automatic methods like __init__. Adding frozen=True makes the instance immutable, meaning you cannot change its fields after creation.
Parts explained:
@dataclass: Decorator to create a dataclass.frozen=True: Makes the dataclass immutable.- Class fields: Define the data attributes.
python
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: int y: int
Example
This example shows how to create a frozen dataclass and what happens if you try to change a field after creation.
python
from dataclasses import dataclass @dataclass(frozen=True) class Point: x: int y: int p = Point(1, 2) print(p) try: p.x = 10 except Exception as e: print(f"Error: {e}")
Output
Point(x=1, y=2)
Error: cannot assign to field 'x'
Common Pitfalls
Trying to modify fields of a frozen dataclass raises an error. Also, frozen dataclasses do not allow using __post_init__ to change fields because they are read-only.
Wrong way: Modifying a field after creation.
Right way: Create a new instance if you need different values.
python
from dataclasses import dataclass @dataclass(frozen=True) class Person: name: str age: int p = Person("Alice", 30) # Wrong: This will raise an error try: p.age = 31 except Exception as e: print(f"Error: {e}") # Right: Create a new instance p2 = Person(p.name, 31) print(p2)
Output
Error: cannot assign to field 'age'
Person(name='Alice', age=31)
Quick Reference
| Feature | Description |
|---|---|
| @dataclass(frozen=True) | Creates an immutable dataclass |
| Immutable fields | Fields cannot be changed after creation |
| Raises error on assignment | Trying to assign to fields raises FrozenInstanceError |
| Use new instance to change data | Create new objects instead of modifying existing ones |
Key Takeaways
Use @dataclass(frozen=True) to make dataclass instances immutable.
Frozen dataclasses prevent changing fields after creation, raising errors on assignment.
To update data, create a new instance instead of modifying an existing one.
Frozen dataclasses do not allow field changes even inside __post_init__.
They are useful for creating hashable, read-only data objects.