Dataclass
In one line
@dataclass auto-generates boilerplate methods (__init__, __repr__, __eq__) for data-heavy classes.
In simple words
The @dataclass decorator (Python 3.7+) eliminates boilerplate for classes that primarily hold data. Instead of writing __init__, __repr__, __eq__ by hand, you declare fields with type hints and the decorator generates them.
Options include frozen=True (immutable), order=True (generates __lt__, __le__ etc.), slots=True (memory efficient). Dataclasses are perfect for config objects, DTOs, database records, and any class where the data matters more than the behavior.
Example
from dataclasses import dataclass, field
@dataclass(frozen=True, order=True)
class Point:
x: float
y: float
tags: list = field(default_factory=list)
p1 = Point(1.0, 2.0)
p2 = Point(1.0, 2.0)
print(p1) # Point(x=1.0, y=2.0, tags=[])
print(p1 == p2) # True — auto-generated __eq__
print(p1.x) # 1.0@dataclass generates __init__, __repr__, __eq__, and __hash__ (when frozen) automatically from type-annotated fields.
Common confusions
Confused with: NamedTuple
The difference: Dataclasses are mutable by default and support inheritance. NamedTuples are always immutable, are real tuples (indexable), and use less memory. Use dataclass for flexibility, NamedTuple for immutable lightweight records.
Related terms
Related Resources
Related Lessons
- Python Dataclasses
Using @dataclass.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.