A dataclass is a class designed mainly to store data with less repeated code.
The @dataclass decorator can generate __init__, __repr__, and comparison behavior from annotated fields.
Use dataclasses for clear records such as products, settings, coordinates, users, and parsed data.
A dataclass keeps field names, types, and default values close together.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
in_stock: bool = True
book = Product("Python Guide", 499)
print(book)
Product(name='Python Guide', price=499, in_stock=True)
The dataclass creates a useful constructor and readable representation automatically.
Simple default values can be assigned directly. Mutable defaults need default_factory.
from dataclasses import dataclass, field
@dataclass
class Cart:
owner: str
items: list[str] = field(default_factory=list)
cart = Cart("Maya")
cart.items.append("Book")
print(cart.items)
['Book']
default_factory creates a fresh list for each Cart object.
A frozen dataclass prevents normal field reassignment after creation.
dataclasses.asdict() turns a dataclass object into a dictionary for serialization or display.
Try this next
0 of 3 completed
It is still a class, but the decorator generates common methods so you write less boilerplate.
Yes. Add methods when behavior belongs with the data, such as total(), label(), or is_valid().
Avoid them when the class mainly manages behavior, resources, inheritance complexity, or strict validation workflows.
Explore 500+ free tutorials across 20+ languages and frameworks.