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=Truemakes instances immutable.order=Trueadds 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
- Defining a Dataclass
- Default Values and field()
- Frozen and Comparison Options
- The attrs Library