How to Create Immutable Data Classes with frozen=True in Python
Create immutable data classes in Python using @dataclass(frozen=True) to prevent attribute modifications after instantiation.
Python code
19 linesfrom dataclasses import dataclass
@dataclass(frozen=True)
class Point:
x: float
y: float
def distance_from_origin(self) -> float:
return (self.x**2 + self.y**2) ** 0.5
if __name__ == "__main__":
p = Point(3.0, 4.0)
print(p)
print(f"Distance from origin: {p.distance_from_origin():.2f}")
try:
p.x = 10.0
except AttributeError as e:
print(f"Cannot modify frozen dataclass: {e}")
Output
Point(x=3.0, y=4.0)
Distance from origin: 5.00
Cannot modify frozen dataclass: cannot assign to field 'x'
How it works
The @dataclass(frozen=True) decorator automatically generates an __init__, __repr__, and other dunder methods while making the instance immutable. When you try to set an attribute, Python raises an AttributeError because the __setattr__ method is overridden to disallow changes. This immutability makes instances hashable (if fields are hashable), which is useful for using them as dictionary keys or in sets. The class-level distance_from_origin method remains usable since it only reads attributes.
Common mistakes
- Assuming frozen dataclasses cannot have any methods—they can, as long as they don't modify state.
- Forgetting that frozen=True makes instance hashable only if all fields are hashable.
- Trying to mutate a field inside a method will raise AttributeError at runtime.
Variations
- Use `@dataclass(frozen=True, order=True)` to get ordering methods for sorting.
- Use `frozen=True` with `slot=True` (Python 3.10+) for memory efficiency and speed.
Real-world use cases
- Modeling immutable value objects like coordinates or configuration records in a data pipeline.
- Using frozen dataclass instances as dictionary keys for caching or counting occurrences.
- Defining API request/response schemas that should not be modified after creation.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.