Introduction
Writing a simple data class in Python used to mean 30 lines of __init__, __repr__, __eq__. Dataclasses (Python 3.7+) generate all of that from type hints. Less boilerplate, same clarity.
This post is the practical guide: enough to use dataclasses well, without the deep internals.
The problem dataclasses solve
# Before: 20+ lines of boilerplate
class User:
def __init__(self, name: str, age: int, email: str = ""):
self.name = name
self.age = age
self.email = email
def __repr__(self):
return f"User(name={self.name!r}, age={self.age!r}, email={self.email!r})"
def __eq__(self, other):
if not isinstance(other, User):
return NotImplemented
return (self.name, self.age, self.email) == (other.name, other.age, other.email)
# After: 4 lines
from dataclasses import dataclass
@dataclass
class User:
name: str
age: int
email: str = ""
Same behavior, 80% less code. __init__, __repr__, __eq__ are generated automatically.
Basic usage
from dataclasses import dataclass
@dataclass
class Point:
x: float
y: float
p = Point(1.0, 2.0)
print(p) # Point(x=1.0, y=2.0)
print(p == Point(1.0, 2.0)) # True
Default values and field()
from dataclasses import dataclass, field
@dataclass
class Config:
host: str = "localhost"
port: int = 8000
tags: list[str] = field(default_factory=list) # mutable default
secret: str = field(default="", repr=False) # hide in repr
Never use mutable defaults directly (tags: list = []) — that’s a classic Python bug. Use field(default_factory=list).
frozen (immutable)
@dataclass(frozen=True)
class Point:
x: float
y: float
p = Point(1, 2)
p.x = 3 # FrozenInstanceError
Frozen dataclasses are hashable → usable as dict keys and set members. Great for value objects.
__post_init__ for validation
@dataclass
class User:
name: str
age: int
def __post_init__(self):
if self.age < 0:
raise ValueError("age must be non-negative")
self.name = self.name.strip().title()
Runs after __init__. Use for validation and derived fields.
init=False and computed fields
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
self.area = self.width * self.height
area isn’t passed to the constructor — it’s computed.
asdict and astuple
from dataclasses import asdict, astuple
p = Point(1.0, 2.0)
asdict(p) # {'x': 1.0, 'y': 2.0}
astuple(p) # (1.0, 2.0)
Handy for JSON serialization and DB inserts.
Dataclasses vs alternatives
| dataclass | NamedTuple | Pydantic | attrs | |
|---|---|---|---|---|
| Mutable | Yes (default) | No | Yes | Yes |
| Type validation | No (hints only) | No | Yes (runtime) | Optional |
| Performance | Fast | Fastest | Slower (validation) | Fast |
| Ecosystem | Built-in | Built-in | Huge (FastAPI) | Third-party |
| Use case | Data containers | Immutable records | API validation | Advanced features |
- dataclass = default choice for plain data containers.
- NamedTuple = when you want tuple unpacking + immutability.
- Pydantic = when you need runtime validation (APIs, config).
- attrs = when you need advanced features (validators, converters, slots).
slots=True (Python 3.10+)
@dataclass(slots=True)
class Point:
x: float
y: float
Uses __slots__ — faster attribute access and lower memory. Recommended for high-volume objects.
Common mistakes
- Mutable defaults —
tags: list = []shares one list across instances. Usefield(default_factory=list). - Forgetting
__post_init__for validation — dataclasses don’t validate types.User(name=42, age="abc")won’t error. - Mixing with inheritance — dataclass inheritance works but field ordering can be tricky (fields without defaults must come first).
- Using for everything — dataclasses are for data. For behavior-heavy classes, regular classes are fine.
Key Concepts
@dataclass= decorator that generates__init__,__repr__,__eq__field()= customize defaults, repr, init, metadatafrozen=True= immutable + hashable__post_init__= validation and derived fieldsslots=True= memory/performance optimization
What to Try Next
- Refactor a Pydantic model to a dataclass when you don’t need validation.
- Use
frozen=Truefor value objects in your FastAPI backend. - Combine with type hints for full static checking.
- Add
slots=Trueto high-volume data classes.
FAQ
Dataclass vs Pydantic — which one?
Dataclass = fast, no validation, built-in. Pydantic = slower, runtime validation, ecosystem (FastAPI). Use dataclass for internal data; Pydantic for API boundaries.
Are dataclasses faster than regular classes?
Slightly faster to define (less code) and similar at runtime. With slots=True, attribute access is faster and memory is lower. For most code, the difference is negligible.
Can I use dataclasses with FastAPI?
Yes — FastAPI prefers Pydantic for request/response (validation + docs), but you can use dataclasses for internal models and convert at the boundary. Pydantic also supports dataclasses via pydantic.dataclasses.