0Pricing
Python Academy · Lesson

Frozen and Comparison Options

Make immutable, ordered dataclasses.

Decorator Options

The @dataclass decorator accepts keyword arguments that control which methods it generates. The most useful are frozen and order.

  • frozen=True makes instances immutable.
  • order=True adds comparison operators.

Frozen Dataclasses

With frozen=True the generated class blocks attribute assignment after construction. Any attempt raises FrozenInstanceError.

from dataclasses import dataclass, FrozenInstanceError

@dataclass(frozen=True)
class Point:
    x: int
    y: int

p = Point(1, 2)
try:
    p.x = 99
except FrozenInstanceError as e:
    print('Cannot modify:', e)

All lessons in this course

  1. Defining a Dataclass
  2. Default Values and field()
  3. Frozen and Comparison Options
  4. The attrs Library
← Back to Python Academy