Dataclasses
Let @dataclass write the boilerplate — __init__, __repr__, and equality — from a few typed fields.
Classes that mostly hold data need a repetitive __init__, a readable __repr__, and often an __eq__. The @dataclass decorator (from the standard library) generates all of that from a few annotated fields.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 0 # a default value
p = Point(3, 4)
print(p) # nice repr, for free
print(p == Point(3, 4)) # value equality, for free
print(Point(5)) # y defaults to 0Without @dataclass you'd hand-write __init__ to assign each field, plus __repr__ and __eq__. The decorator reads the class-level type annotations and does it for you.
#Handy options
from dataclasses import dataclass
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
v1 = Version(1, 2)
print(v1 < Version(1, 5)) # order=True gives comparisons
# v1.major = 2 # frozen=True -> raises FrozenInstanceErrorWhen to reach for it
Use a dataclass whenever a class is mostly a bundle of values (config, records, DTOs, coordinates). frozen=True makes instances immutable (and hashable); order=True adds <, >, etc. For heavy behavior, a regular class is still the right call.
What does @dataclass generate for you from the annotated fields?
Key takeaways
- `@dataclass` auto-generates `__init__`, `__repr__`, and `__eq__` from annotated fields.
- Fields are declared as class-level annotations: `x: int`, with optional defaults (`y: int = 0`).
- `frozen=True` makes instances immutable; `order=True` adds comparison operators.
- Ideal for value/record classes; use a regular class when behavior dominates.
What does this print?
from dataclasses import dataclass
@dataclass
class P:
x: int
y: int = 0
print(P(3))What does this print?
from dataclasses import dataclass
@dataclass
class P:
x: int
y: int
print(P(1, 2) == P(1, 2))Complete the line so instances are immutable.
@dataclass(=True) class Point: x: int
Turn this plain class into a dataclass with fields title: str and pages: int (default 0):
``python class Book: def __init__(self, title, pages=0): self.title = title self.pages = pages ``
Try it live — edit the code and hit Run to execute real Python: