By WebNest Studio Engineering Team
Python Tutorial
Dataclasses in Python
Many classes exist mainly to hold data: a Product with a name and a price, an Order with items and a status. Writing their __init__, __repr__ and __eq__ by hand is repetitive and error-prone. The dataclasses module generates them from type-annotated fields.
This lesson covers @dataclass, default values and field(), immutability with frozen=True, ordering, __post_init__ validation, slots, keyword-only fields, and converting dataclasses to dicts.
Why it matters
A great many classes exist only to hold a few fields. Writing __init__, __repr__ and __eq__ for each by hand is repetitive and easy to get out of step. @dataclass generates them from the field list, and it is now the standard way to define such classes; Pydantic models, used throughout FastAPI, follow the same style.
Basic Dataclasses
Decorate a class with @dataclass and declare fields with type annotations. Python generates __init__, a readable __repr__ and field-by-field __eq__. Type hints are documentation for tools; they are not enforced at runtime.
Defaults and field()
Fields with defaults must come after fields without. Mutable defaults are forbidden directly — use field(default_factory=list). field() also controls whether a field appears in __repr__ (repr=False for secrets), in comparisons, or in __init__ (init=False for computed fields).
Options: frozen, order, slots, kw_only
frozen=True makes instances immutable and hashable — good for value objects and dict keys. order=True generates comparison methods using fields in order. slots=True uses __slots__ for lower memory use and faster attribute access. kw_only=True forces keyword arguments for clearer construction.
Validation and Conversion
__post_init__ runs after the generated __init__ — use it to validate or derive values. dataclasses.asdict() and astuple() convert to plain structures (for JSON), and replace() creates a modified copy. For validation and parsing of external data (API input), Pydantic models (used by FastAPI) go further.
Examples
A basic dataclass versus a hand-written class
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
def total(self) -> float:
return self.price * self.quantity
p = Product("Pen", 10.0, 5)
print(p)
print(p == Product("Pen", 10.0, 5), p.total())
print(Product("Book", 250.0))
Product(name='Pen', price=10.0, quantity=5)
True 50.0
Product(name='Book', price=250.0, quantity=0)
field(), default_factory, __post_init__ and hidden fields
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: str
items: list[str] = field(default_factory=list)
prices: list[float] = field(default_factory=list)
api_token: str = field(default="", repr=False)
total: float = field(init=False)
def __post_init__(self):
if not self.order_id.startswith("WN-"):
raise ValueError("order id must start with WN-")
self.total = sum(self.prices)
o = Order("WN-101", ["pen", "book"], [10, 250], api_token="secret")
print(o)
print(Order("WN-102").items is not Order("WN-103").items)
try:
Order("101")
except ValueError as e:
print("ValueError:", e)
Order(order_id='WN-101', items=['pen', 'book'], prices=[10, 250], total=260)
True
ValueError: order id must start with WN-
frozen, order, slots, kw_only, asdict and replace
from dataclasses import dataclass, asdict, astuple, replace, FrozenInstanceError
@dataclass(frozen=True, order=True, slots=True)
class Version:
major: int
minor: int
patch: int = 0
@dataclass(kw_only=True)
class Settings:
theme: str = "light"
page_size: int = 20
v1, v2 = Version(3, 12), Version(3, 9, 4)
print(sorted([v1, v2]), v1 > v2, {v1: "current"})
try:
v1.major = 4
except FrozenInstanceError as e:
print("FrozenInstanceError:", e)
print(replace(v1, patch=1), asdict(v1), astuple(v2))
print(Settings(page_size=50))
try:
Settings("dark")
except TypeError as e:
print("TypeError:", e)
[Version(major=3, minor=9, patch=4), Version(major=3, minor=12, patch=0)] True {Version(major=3, minor=12, patch=0): 'current'}
FrozenInstanceError: cannot assign to field 'major'
Version(major=3, minor=12, patch=1) {'major': 3, 'minor': 12, 'patch': 0} (3, 9, 4)
Settings(theme='light', page_size=50)
TypeError: Settings.__init__() takes 1 positional argument but 2 were given
Common Mistakes
- Using items: list = [] as a default (ValueError: mutable default) — use field(default_factory=list).
- Putting a field without a default after one with a default.
- Assuming type hints are enforced at runtime; validate in __post_init__ or use Pydantic.
- Mutating a frozen dataclass instead of using replace().
Exercise
Define a dataclass Point with an integer x and an integer y that defaults to 0, and a dataclass Cart whose items field is a list that is separate for every cart.
Expected output: Point(x=1, y=0), True, [] (one per line)
from dataclasses import dataclass, field
# TODO: dataclass Point with x: int and y: int = 0
# TODO: dataclass Cart with items: list, each cart getting its own empty list
print(Point(1))
print(Point(1, 2) == Point(1, 2))
first = Cart()
first.items.append("pen")
second = Cart()
print(second.items)
Show hints
- A field is declared as
name: type, with an optional= default. - A mutable default must be given as
field(default_factory=list).
Show solution
from dataclasses import dataclass, field
@dataclass
class Point:
x: int
y: int = 0
@dataclass
class Cart:
items: list = field(default_factory=list)
print(Point(1))
print(Point(1, 2) == Point(1, 2))
first = Cart()
first.items.append("pen")
second = Cart()
print(second.items)
Quick quiz
1. Which methods does @dataclass generate by default?
- A. __init__, __repr__ and __eq__
- B. Only __init__
- C. All comparison methods
- D. None
Show answer
A. Ordering methods are added with order=True and hashing with frozen=True.
2. What does @dataclass(frozen=True) do?
- A. Makes the class abstract
- B. Hides the fields
- C. Speeds up the class
- D. Makes instances immutable; assigning to a field raises an error
Show answer
D. A frozen dataclass is also hashable, so it can be used as a dictionary key.
3. What happens if a dataclass field is declared as items: list = []?
- A. ValueError is raised when the class is defined
- B. Each object gets its own list
- C. All objects share one list silently
- D. The field is ignored
Show answer
A. Dataclasses refuse mutable defaults to prevent the shared-list bug. Use default_factory.
Interview questions
What is a dataclass and when would you use one?
Show answer
A dataclass is a class decorated with @dataclass, for which Python generates __init__, __repr__ and __eq__ from the annotated fields. It is used for classes whose main job is to hold data, such as a configuration object or a record read from a file. It remains an ordinary class, so methods and properties can be added.
What is __post_init__ used for?
Show answer
It is a method that the generated __init__ calls after the fields have been assigned. It is the place for validation, for converting values, and for setting fields that are calculated from others, which are declared with field(init=False) so that they are not constructor parameters.
Key Points to Remember
- @dataclass generates __init__, __repr__ and __eq__ from annotated fields.
- Use field(default_factory=...) for mutable defaults; field() also controls repr/init/compare.
- frozen, order, slots and kw_only options tailor behaviour.
- __post_init__ validates or derives values; asdict/astuple/replace convert and copy.
Practice in the playground
Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.
Run the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Written by
WebNest Studio Engineering Team
Practical lessons from developers working with Java, Python, React, databases and production systems.
Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering