Say you’re tracking a bike shop’s stock: a $59.99 helmet, a $34.50 lock and $8.75 chain lube. A plain class needs about 15 lines of __init__, __repr__ and __eq__ before it stores a single price.
A Python dataclass removes all of that. Put @dataclass above a class, list the fields with type hints, and Python writes those methods for you when the class is created.
In this tutorial, I’ll show you how to use a python dataclass on one small inventory, from the first decorator to defaults, validation, frozen objects, sorting, JSON, slots and inheritance.
What Is a Python Dataclass?
A dataclass is a regular class that the dataclasses module fills in for you, so nothing about object-oriented Python changes. It reads the annotated class attributes and generates the boilerplate you’d otherwise type by hand.
Here’s that boilerplate written the long way, the kind of constructor in Python most of us learned first:
class Product:
def __init__(self, name, price, quantity=0):
self.name = name
self.price = price
self.quantity = quantity
def __repr__(self):
return (f"Product(name={self.name!r}, price={self.price!r}, "
f"quantity={self.quantity!r})")
def __eq__(self, other):
if not isinstance(other, Product):
return NotImplemented
return (self.name, self.price, self.quantity) == (
other.name, other.price, other.quantity)
helmet = Product("Trail Helmet", 59.99, 4)
print(helmet)
print(helmet == Product("Trail Helmet", 59.99, 4))
Output:
Product(name='Trail Helmet', price=59.99, quantity=4)
True
It works, but every new field means editing three methods. Forget one and == quietly compares the wrong data. I ran every example in this post on Python 3.14.8.
The @dataclass decorator was added in Python 3.7 (PEP 557). If you want the full side-by-side, I compared a Python dataclass vs a normal class in a separate post.
The Sample Bike Shop Inventory for These Dataclass Examples
Every example uses the same three products from Ridgeline Cycles, a small shop in Boulder, Colorado:
- Trail Helmet: $59.99, 4 in stock
- U-Lock: $34.50, no quantity given (this one tests default values)
- Chain Lube: $8.75, 12 in stock
The U-Lock row is the tricky one. Later we’ll also feed the class a negative price and a list of tags, because those are exactly the inputs that break a careless dataclass.
Method 1: Create a Python Dataclass with @dataclass (Recommended)
Use this for any class that mainly holds data: records from a CSV, API payloads, config values or rows like our inventory. Same three items, now written as a dataclass.
Here’s the code:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
def stock_value(self):
return round(self.price * self.quantity, 2)
inventory = [
Product("Trail Helmet", 59.99, 4),
Product("U-Lock", 34.50),
Product("Chain Lube", 8.75, 12),
]
for item in inventory:
print(item, f"-> ${item.stock_value():,.2f}")
print(inventory[0] == Product("Trail Helmet", 59.99, 4))
Output:
Product(name='Trail Helmet', price=59.99, quantity=4) -> $239.96
Product(name='U-Lock', price=34.5, quantity=0) -> $0.00
Product(name='Chain Lube', price=8.75, quantity=12) -> $105.00
True
Here’s the same script running in VS Code:

The helmet stock is worth $239.96, the lube $105.00, and the U-Lock shows $0.00 because it took the default quantity of 0.
How does this code work?
@dataclass scans the class for annotations: name: str, price: float and quantity: int = 0. Each one becomes a field, in that order.
From those fields it writes __init__(self, name, price, quantity=0), a readable __repr__ and an __eq__ that compares fields as a tuple. That’s why the last line prints True for two separate objects.
Normal methods like stock_value() still work. The decorator only adds methods, it doesn’t change what a class is, so everything from class decorators in Python applies here too.
Important: type hints aren’t checked at runtime. Product("U-Lock", "cheap") runs fine, so validate real input yourself (Method 3).
Method 2: Set Default Values with field() and default_factory
Defaults like quantity: int = 0 are fine for numbers and strings. A list is different. Same items, but now each product gets a tags list:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
tags: list = []
Output:
Traceback (most recent call last):
File "C:\pyguides\mutable_default.py", line 4, in <module>
@dataclass
^^^^^^^^^
File "C:\pyguides\uvpython\cpython-3.14.8-windows-x86_64-none\Lib\dataclasses.py", line 1451, in dataclass
return wrap(cls)
File "C:\pyguides\uvpython\cpython-3.14.8-windows-x86_64-none\Lib\dataclasses.py", line 1441, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
frozen, match_args, kw_only, slots,
weakref_slot)
File "C:\pyguides\uvpython\cpython-3.14.8-windows-x86_64-none\Lib\dataclasses.py", line 1066, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\pyguides\uvpython\cpython-3.14.8-windows-x86_64-none\Lib\dataclasses.py", line 917, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
f'{f.name} is not allowed: use default_factory')
ValueError: mutable default <class 'list'> for field tags is not allowed: use default_factory

The class never gets created. Python raises the error at definition time to protect you from one list being shared by every product.
The fix is field(default_factory=list), which calls list() for each new object. I also hid the wholesale cost from the printout:
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
quantity: int = 0
tags: list[str] = field(default_factory=list)
cost: float = field(default=0.0, repr=False)
helmet = Product("Trail Helmet", 59.99, 4, cost=31.20)
lock = Product("U-Lock", 34.50)
helmet.tags.append("safety")
print(helmet)
print(lock)
print(f"Margin per helmet: ${helmet.price - helmet.cost:.2f}")
Output:
Product(name='Trail Helmet', price=59.99, quantity=4, tags=['safety'])
Product(name='U-Lock', price=34.5, quantity=0, tags=[])
Margin per helmet: $28.79
The helmet has tags=['safety'], the U-Lock still has its own empty list, and the margin per helmet is $28.79.
How does this code work?
default_factory takes any zero-argument callable: list, dict, set or your own function. Appending to helmet.tags can’t leak into lock.tags.
field(repr=False) keeps cost out of the printout, which is handy for prices, tokens and passwords. For every field() option plus Optional and Union hints, see default values and type hints in Python dataclasses.
Method 3: Validate Dataclass Fields with __post_init__
The generated __init__ just stores what you pass. When you need to clean or check values, add __post_init__, which runs right after it. Here it rejects the negative price from our sample and builds a SKU:
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
quantity: int = 0
sku: str = field(init=False)
def __post_init__(self):
if self.price <= 0:
raise ValueError(f"{self.name}: price must be above $0.00")
self.name = self.name.strip().title()
self.sku = "RC-" + self.name[:4].upper()
print(Product(" chain lube ", 8.75, 12))
print(Product("Saddle Bag", -19.99))
Output:
Product(name='Chain Lube', price=8.75, quantity=12, sku='RC-CHAI')
Traceback (most recent call last):
File "C:\pyguides\pydemo\post_init.py", line 19, in <module>
print(Product("Saddle Bag", -19.99))
~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 6, in __init__
File "C:\pyguides\pydemo\post_init.py", line 13, in __post_init__
raise ValueError(f"{self.name}: price must be above $0.00")
ValueError: Saddle Bag: price must be above $0.00

" chain lube " became Chain Lube with SKU RC-CHAI. The $-19.99 saddle bag raised a ValueError before any object existed.
How does this code work?
field(init=False) leaves sku out of the constructor, so callers can’t pass it. __post_init__ sets it from the cleaned name instead.
Raising inside __post_init__ stops the object from being returned, so bad data never reaches the rest of your code.
Pro Tip: for heavy validation of user input or JSON, a library like Pydantic does type checking for you. For internal data, __post_init__ is usually all I need.
Method 4: Make a Dataclass Immutable with frozen=True
Prices change, but some records shouldn’t change after they’re created: a receipt, a setting or a dictionary key. frozen=True blocks assignment. Same sample data, with the class now frozen:
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Product:
name: str
price: float
quantity: int = 0
helmet = Product("Trail Helmet", 59.99, 4)
sale = replace(helmet, price=49.99)
print(sale)
print(len({helmet, sale, Product("Trail Helmet", 59.99, 4)}))
helmet.price = 39.99
Output:
Product(name='Trail Helmet', price=49.99, quantity=4)
2
Traceback (most recent call last):
File "C:\pyguides\pydemo\frozen_product.py", line 16, in <module>
helmet.price = 39.99
^^^^^^^^^^^^
File "<string>", line 17, in __setattr__
dataclasses.FrozenInstanceError: cannot assign to field 'price'

replace() returned a new helmet at $49.99, the set kept 2 unique products, and helmet.price = 39.99 raised FrozenInstanceError.
How does this code work?
Frozen dataclasses replace __setattr__ with a method that raises, so the fields can’t be reassigned after __init__.
Because the values can’t change, Python also generates __hash__. That’s why the two equal helmets count once in the set. To “change” a frozen object, make a modified copy with dataclasses.replace(), much like you’d copy a list in Python before editing it.
Note: frozen is shallow. A list field inside a frozen dataclass can still be appended to, so use a tuple when it must stay fixed.
Method 5: Compare and Sort Dataclass Objects with order=True
By default you get == but not <. With order=True, the dataclass compares fields in order, so I moved price first and switched the other fields off with compare=False:
from dataclasses import dataclass, field
@dataclass(order=True)
class Product:
price: float
name: str = field(compare=False)
quantity: int = field(default=0, compare=False)
inventory = [
Product(59.99, "Trail Helmet", 4),
Product(34.50, "U-Lock"),
Product(8.75, "Chain Lube", 12),
]
for item in sorted(inventory):
print(f"${item.price:>6.2f} {item.name}")
print(Product(34.50, "U-Lock") == Product(34.50, "Kryptonite Lock"))
print(max(inventory).name)
Output:
$ 8.75 Chain Lube
$ 34.50 U-Lock
$ 59.99 Trail Helmet
True
Trail Helmet

sorted() lists Chain Lube at $8.75, U-Lock at $34.50 and Trail Helmet at $59.99. Two locks at the same price compare equal, and max() returns the helmet.
How does this code work?
order=True adds __lt__, __le__, __gt__ and __ge__. Each one compares the fields as a tuple, but only fields left with compare=True.
Reordering fields just to sort is a trade-off. When you need several sort orders, keep the natural field order and pass key= instead, as shown in sorting a list of objects by attribute.
How Do You Convert a Dataclass to a Dictionary or JSON?
Sooner or later the inventory has to go to an API or a file. asdict() turns a dataclass into a dict, and astuple() into a tuple, recursing into nested dataclasses and lists:
import json
from dataclasses import dataclass, field, asdict, astuple
@dataclass
class Product:
name: str
price: float
quantity: int = 0
tags: list[str] = field(default_factory=list)
@dataclass
class Order:
order_id: str
items: list[Product]
order = Order("RC-2026-1104", [Product("U-Lock", 34.50, 1, ["security"]),
Product("Chain Lube", 8.75, 2)])
print(astuple(order.items[1]))
print(json.dumps(asdict(order), indent=2))
Output:
('Chain Lube', 8.75, 2, [])
{
"order_id": "RC-2026-1104",
"items": [
{
"name": "U-Lock",
"price": 34.5,
"quantity": 1,
"tags": [
"security"
]
},
{
"name": "Chain Lube",
"price": 8.75,
"quantity": 2,
"tags": []
}
]
}
The lube became ('Chain Lube', 8.75, 2, []), and the whole order, products included, dumped to JSON with order ID RC-2026-1104.
How does this code work?
json.dumps() can’t serialize a dataclass directly, but it handles the plain dict that asdict() returns. Each nested Product became its own dict automatically.
astuple() is useful for CSV rows or database inserts. The field types, like list[Product], follow the same rules as Python tuple type hints.
Use kw_only and slots in a Python Dataclass (3.10+)
Python 3.10 added two options I now use on most new dataclasses. kw_only=True forces named arguments, and slots=True stores fields in __slots__ for less memory and faster access:
from dataclasses import dataclass, field, fields
@dataclass(kw_only=True, slots=True)
class Product:
name: str
price: float
quantity: int = 0
aisle: str = field(default="A1", doc="Store aisle code")
lock = Product(name="U-Lock", price=34.50, aisle="C3")
print(lock)
print(Product.__slots__)
print(fields(Product)[3].doc)
try:
Product("U-Lock", 34.50)
except TypeError as err:
print("TypeError:", err)
try:
lock.color = "black"
except AttributeError as err:
print("AttributeError:", err)
Output:
Product(name='U-Lock', price=34.5, quantity=0, aisle='C3')
{'name': None, 'price': None, 'quantity': None, 'aisle': 'Store aisle code'}
Store aisle code
TypeError: Product.__init__() takes 1 positional argument but 3 were given
AttributeError: 'Product' object has no attribute 'color' and no __dict__ for setting new attributes
The U-Lock printed with aisle='C3', positional arguments raised a TypeError, and adding an undeclared color attribute failed.
How does this code work?
Keyword-only arguments make calls like Product(name="U-Lock", price=34.50) readable and safe to reorder. Slots drop the per-object __dict__ attribute, so typos like lock.colour fail loudly instead of creating a new attribute.
The doc= argument to field() is new in Python 3.14. With slots=True, my run showed it twice: on the field object and as the value for aisle in the __slots__ dict, which is where help() reads it.
Inherit from a Python Dataclass
A subclass can add fields to a dataclass. Here a Bike extends our Product with a frame size, and the first try fails:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
@dataclass
class Bike(Product):
frame_size: str
Output:
Traceback (most recent call last):
File "C:\pyguides\pydemo\bike.py", line 11, in <module>
@dataclass
^^^^^^^^^
...
TypeError: non-default argument 'frame_size' follows default argument 'quantity'
Fields are collected base-first, so frame_size would land after quantity=0 in __init__. A required parameter can’t follow an optional one.
Making the subclass keyword-only fixes it, because keyword-only fields are moved to the end:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
@dataclass(kw_only=True)
class Bike(Product):
frame_size: str
def label(self):
return f"{self.name} ({self.frame_size}) ${self.price:,.2f}"
gravel = Bike("Gravel 2", 1249.00, 2, frame_size="54 cm")
print(gravel)
print(gravel.label(), isinstance(gravel, Product))
Output:
Bike(name='Gravel 2', price=1249.0, quantity=2, frame_size='54 cm')
Gravel 2 (54 cm) $1,249.00 True
The 54 cm gravel bike prints all four fields, its label shows $1,249.00, and it’s still an instance of Product, which you can confirm with isinstance() and issubclass().
I’d keep dataclass hierarchies shallow, one or two levels. Deep trees are where classmethod factories or plain composition read better.
Which Dataclass Option Should You Use?
| Option | Use it when | Python |
|---|---|---|
@dataclass | You want a simple record with readable output | 3.7+ |
field(default_factory=...) | A default is a list, dict or set | 3.7+ |
__post_init__ | Values need cleaning, checking or computing | 3.7+ |
frozen=True | Objects must not change, or you need them as dict keys | 3.7+ |
order=True | Objects need one natural sort order | 3.7+ |
kw_only=True, slots=True | Many fields, lots of objects, or subclasses | 3.10+ |
If the record is tiny and never changes, a namedtuple can be lighter. My Python dataclass vs namedtuple guide covers when each one wins.
Things to Keep in Mind
- Never use a list, dict or set as a plain default; use
field(default_factory=...). - Type hints aren’t enforced, so validate outside input in
__post_init__. - Fields without defaults must come first, or use
kw_only=True. frozen=Trueis shallow; store tuples, not lists, in frozen records.order=Truecompares fields in definition order, so put the sort field first.
These guides go well with what you just built:
- Python metaclasses tutorial
- Nested classes in Python
- Abstract base classes in Python
- __new__ vs __init__ in Python
Frequently Asked Questions
What is a Python dataclass used for?
It’s used for classes that mainly store data. @dataclass writes __init__, __repr__ and __eq__ from the type-annotated fields, so you skip the boilerplate.
Does a Python dataclass check types at runtime?
No. The type hints define the fields, but Python doesn’t enforce them. Add checks in __post_init__ or use a validation library such as Pydantic.
Why does my dataclass say mutable default is not allowed?
A list, dict or set default would be shared by every object. Use field(default_factory=list) so each object gets its own new list.
How do I make a dataclass immutable?
Use @dataclass(frozen=True). Assigning to a field then raises FrozenInstanceError, and dataclasses.replace() creates a changed copy.
How do I convert a dataclass to JSON?
Call dataclasses.asdict(obj) to get a plain dict, then pass it to json.dumps(). Nested dataclasses are converted too.
Where is the dataclasses module documented?
See dataclasses in the Python standard library documentation.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn