Many classes exist mainly to hold data: a student, an order, a point. Writing __init__, __repr__ and __eq__ for each one is repetitive. The @dataclass decorator, available since Python 3.7, generates these methods from a list of typed fields, so a complete data class takes just a few lines. This lesson covers defaults, mutable fields, frozen and ordered dataclasses, and validation.
In this lesson you will learn
- Declaring a dataclass with typed fields
- What
@dataclassgenerates for you - Default values and
field(default_factory=list) - Frozen (immutable) and ordered dataclasses
__post_init__,replace()andasdict()
This lesson builds on Classes and Objects and Type Hints.
A First Dataclass
from dataclasses import dataclass, field
@dataclass
class Student:
name: str
dept: str
cgpa: float = 0.0
courses: list[str] = field(default_factory=list) # a new list for each object
def is_honours(self) -> bool:
return self.cgpa >= 3.75
s1 = Student("Nusrat", "CSE", 3.82)
s2 = Student("Nusrat", "CSE", 3.82)
s3 = Student("Rafi", "EEE")
s3.courses.append("Circuits")
print(s1) # generated __repr__
print(s1 == s2, s1 is s2) # generated __eq__
print(s3, s1.is_honours(), s3.is_honours())
Output
Student(name='Nusrat', dept='CSE', cgpa=3.82, courses=[])
True False
Student(name='Rafi', dept='EEE', cgpa=0.0, courses=['Circuits']) True False
- Each annotated class variable becomes a field.
@dataclasswrites an__init__that takes the fields in order, a readable__repr__, and an__eq__that compares field values. s1 == s2is true because their fields match, although they are different objects (s1 is s2is false).- Fields with defaults, like
cgpa: float = 0.0, must come after fields without defaults. - A list cannot be a plain default, because every object would share it (the same trap as mutable default arguments).
field(default_factory=list)creates a fresh list for each object. - Dataclasses are normal classes, so you can add methods such as
is_honours.
Frozen, Ordered and Validated Dataclasses
from dataclasses import dataclass, field, asdict, replace
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int
patch: int = 0
def __str__(self) -> str:
return f"{self.major}.{self.minor}.{self.patch}"
v = [Version(1, 10), Version(1, 2, 5), Version(2, 0)]
print([str(x) for x in sorted(v)]) # order=True compares fields in order
print(Version(1, 2) < Version(1, 10))
try:
v[0].major = 9 # frozen: fields cannot change
except Exception as e:
print(type(e).__name__)
print(replace(v[0], patch=1)) # copy with one field changed
print({Version(1, 0): "first"}) # frozen dataclasses are hashable
@dataclass
class Order:
item: str
qty: int
price: float
total: float = field(init=False)
def __post_init__(self): # runs after the generated __init__
if self.qty <= 0:
raise ValueError("qty must be positive")
self.total = self.qty * self.price
o = Order("notebook", 3, 45.5)
print(o, asdict(o))
Output
['1.2.5', '1.10.0', '2.0.0']
True
FrozenInstanceError
1.10.1
{Version(major=1, minor=0, patch=0): 'first'}
Order(item='notebook', qty=3, price=45.5, total=136.5) {'item': 'notebook', 'qty': 3, 'price': 45.5, 'total': 136.5}
order=Truegenerates<,>and friends, comparing fields in the order they are declared, like tuples. So version 1.2.5 sorts before 1.10.0, which plain string sorting would get wrong.frozen=Truemakes objects immutable: assigning a field raisesFrozenInstanceError. Frozen dataclasses are also hashable, so they can be dictionary keys and set members.replace(obj, field=value)returns a modified copy, the usual way to “change” a frozen object.__post_init__runs right after the generated__init__. Use it for validation and for calculated fields markedfield(init=False).asdict()converts a dataclass to a dictionary, ready for JSON.
Dataclass vs Alternatives
| Regular class | namedtuple | dataclass | |
|---|---|---|---|
| Boilerplate | Write everything | None | Very little |
| Mutable | Yes | No | Yes, or frozen |
| Defaults and methods | Yes | Limited | Yes |
| Type hints required | No | No | Yes |
| Behaves like a tuple | No | Yes | No |
Common Mistakes
- Using
courses: list = []; Python raisesValueError. Usefield(default_factory=list). - Forgetting the type annotation;
name = "x"without a type is a class attribute, not a field. - Placing a field without a default after one with a default, which is a
TypeError. - Expecting type hints to be enforced; validate in
__post_init__if needed.
Practice Exercises
Exercise 1. Create a dataclass Book with title, author and a default pages of 100, and print an instance.
Show answer
from dataclasses import dataclass
@dataclass
class Book:
title: str
author: str
pages: int = 100
print(Book("Padma Nadir Majhi", "Manik Bandopadhyay"))
Exercise 2. Make a frozen dataclass Money(amount: int, currency: str) that rejects negative amounts.
Show answer
@dataclass(frozen=True)
class Money:
amount: int
currency: str = "BDT"
def __post_init__(self):
if self.amount < 0:
raise ValueError("amount cannot be negative")
Frequently Asked Questions
Can dataclasses use inheritance?
Yes. A dataclass can inherit from another, and the child’s fields are added after the parent’s. The rule about defaults still applies across both.
What does slots=True do?
@dataclass(slots=True) (Python 3.10+) stores fields in fixed slots instead of a per-object dictionary, which saves memory and prevents adding new attributes by mistake.
Summary
@dataclassgenerates__init__,__repr__and__eq__from typed fields.- Use
field(default_factory=...)for list and dict defaults. frozen=Truemakes objects immutable and hashable;order=Trueadds comparisons.- Validate and compute fields in
__post_init__.
Next: Python Context Managers.
