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.

Easy Python 3.7+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

19 lines
Python 3.7+
from 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

stdout
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

  1. Use `@dataclass(frozen=True, order=True)` to get ordering methods for sorting.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.