Python Dataclasses
What you will learn
- What a dataclass is and why it saves code
- Fields, defaults, and
default_factory frozen,orderand hashing__post_init__andfield(...)optionsasdict,astuple,replace- Inheritance,
slotsandkw_only
1. The problem: classes that only hold data
Many classes exist just to hold a few values. A plain class needs a lot of repeated code (lessons 13.1 and 13.7):
class Plain:
def __init__(self, x, y=0):
self.x, self.y = x, y
print(Plain(1, 2))
print(Plain(1) == Plain(1))
<__main__.Plain object at 0x0000025733D1D6A0>
False
The printout is useless and == compares identity. To fix both you would write __repr__ and __eq__ by hand. The dataclasses module writes them for you.
2. A first dataclass
Put the @dataclass decorator above a class and list the fields as annotated names (lesson 11.8):
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int = 0
p = Point(1, 2)
print(p)
print(p == Point(1, 2), p is Point(1, 2))
print(Point(5))
Point(x=1, y=2)
True False
Point(x=5, y=0)
Python generated:
__init__(self, x, y=0), which stores the fields;__repr__, showing the class name and fields;__eq__, comparing the fields as a tuple (same class required).
Fields with a default (y: int = 0) must come after those without one. Forgetting a required field is an error:
Point()
TypeError: Point.__init__() missing 1 required positional argument: 'x'
The annotations are not checked at run time: Any1("text") for a field typed int is accepted. They document the fields, and tools such as type checkers use them (lesson 19.1).
Quick check: which three methods does @dataclass create by default?
__init__, __repr__ and __eq__.
3. Mutable defaults: default_factory
A default like [] would be shared by all objects (lesson 11.9), so dataclasses refuse it:
@dataclass
class Bad:
items: list = []
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory
Use field(default_factory=...), which calls a function to make a fresh value for every object:
from dataclasses import field
@dataclass
class Cart:
owner: str
items: list = field(default_factory=list)
a, b = Cart("A"), Cart("B")
a.items.append("pen")
print(a, b)
Cart(owner='A', items=['pen']) Cart(owner='B', items=[])
Each cart has its own list. Use default_factory=dict or set the same way.
4. Dataclasses are normal classes
You can add methods, properties and class methods as usual, and the fields stay mutable:
@dataclass
class Student:
name: str
grades: list[int] = field(default_factory=list)
def average(self):
return sum(self.grades) / len(self.grades) if self.grades else 0.0
def add(self, g):
self.grades.append(g)
return self
s = Student("Rina").add(80).add(90)
print(s, s.average())
Student(name='Rina', grades=[80, 90]) 85.0
5. Frozen: immutable and hashable
By default, a dataclass is mutable, and because it defines __eq__, it is unhashable (lesson 13.8):
p = Point(1, 2)
p.x = 10
print(p)
hash(p)
Point(x=10, y=2)
TypeError: unhashable type: 'Point'
@dataclass(frozen=True) makes the fields read-only, and Python then also writes a __hash__, so the objects can be dictionary keys and set members:
@dataclass(frozen=True)
class FP:
x: int
y: int = 0
f = FP(1, 2)
try:
f.x = 5
except Exception as e:
print(type(e).__name__, e)
print(hash(f) == hash(FP(1, 2)), {f: "a"}[FP(1, 2)])
FrozenInstanceError cannot assign to field 'x'
True a
Frozen dataclasses are a neat way to make immutable value objects, with no hand-written __eq__ or __hash__.
6. Ordering
@dataclass(order=True) adds <, <=, >, >=, comparing the fields in the order they are declared:
@dataclass(order=True)
class Ver:
major: int
minor: int
print(Ver(1, 9) < Ver(1, 10))
print(sorted([Ver(2, 0), Ver(1, 10), Ver(1, 9)]))
print(max(Ver(1, 2), Ver(1, 3)))
True
[Ver(major=1, minor=9), Ver(major=1, minor=10), Ver(major=2, minor=0)]
Ver(major=1, minor=3)
This replaces __lt__ plus total_ordering from lesson 13.8. The field order decides the sort order.
7. post_init and field options
The generated __init__ calls __post_init__ at the end, if you define it. Use it for validation and computed fields. A field marked init=False is not an __init__ argument:
@dataclass
class Rect:
w: float
h: float
area: float = field(init=False)
def __post_init__(self):
if self.w < 0 or self.h < 0:
raise ValueError("negative size")
self.area = self.w * self.h
print(Rect(2, 3))
Rect(-1, 2)
Rect(w=2, h=3, area=6)
ValueError: negative size
The main options of field(...):
| Option | Meaning |
|---|---|
default=... |
a plain default value |
default_factory=f |
call f() for each new object |
init=False |
not a parameter of __init__ |
repr=False |
leave out of the printout |
compare=False |
ignore in == and ordering |
@dataclass
class Emp:
name: str
salary: float = field(compare=False)
print(Emp("A", 100) == Emp("A", 200))
True
8. Converting and copying
Helper functions in dataclasses:
from dataclasses import asdict, astuple, replace, fields
p = Point(1, 2)
print(asdict(p))
print(astuple(p))
print(replace(p, y=9))
print([f.name for f in fields(p)])
{'x': 1, 'y': 2}
(1, 2)
Point(x=1, y=9)
['x', 'y']
asdictgives a dictionary (nested dataclasses are converted too), handy for JSON (lesson 15.7).replacemakes a copy with some fields changed, the usual way to "modify" a frozen object.
9. Inheritance, slots and kw_only
A dataclass can inherit from another; the parent's fields come first:
@dataclass
class Base:
id: int
@dataclass
class Child(Base):
name: str = "x"
print(Child(1), Child(2, "y"))
Child(id=1, name='x') Child(id=2, name='y')
Two more options (Python 3.10+):
slots=Truesaves memory and blocks new attributes (lesson 13.14):
@dataclass(slots=True)
class S:
a: int
print(S(1), hasattr(S(1), "__dict__"))
S(a=1) False
kw_only=Truemakes all fields keyword-only, which avoids mixing up positions:
@dataclass(kw_only=True)
class K:
a: int
b: int = 2
print(K(a=1))
K(1)
K(a=1, b=2)
TypeError: K.__init__() takes 1 positional argument but 2 were given
10. When to use a dataclass
| Use a dataclass for | Use something else for |
|---|---|
| records with several fields (a point, an order line, a settings object) | a class with little data and mostly behaviour |
| values you compare, print, sort or store in sets | a plain tuple or a namedtuple for a tiny fixed record |
| replacing a dictionary with fixed keys (clearer, typo-safe) | a dictionary whose keys really vary |
immutable values (frozen=True) |
objects that need complex setup beyond __post_init__ |
Worked example: an order line and an order
Model a shop order with immutable products, order lines that compute their own totals, and an order that holds the lines.
from dataclasses import dataclass, field, asdict, replace
@dataclass(frozen=True)
class Product:
name: str
price: float
@dataclass
class Line:
product: Product
qty: int = 1
def __post_init__(self):
if self.qty < 1:
raise ValueError("qty must be at least 1")
@property
def total(self):
return round(self.product.price * self.qty, 2)
@dataclass
class Order:
customer: str
lines: list[Line] = field(default_factory=list)
def add(self, product, qty=1):
self.lines.append(Line(product, qty))
return self
@property
def total(self):
return round(sum(line.total for line in self.lines), 2)
pen = Product("Pen", 1.5)
book = Product("Book", 12.0)
order = Order("Rina").add(pen, 4).add(book)
print(order)
print(order.total)
print(asdict(order.lines[0]))
pen2 = replace(pen, price=1.75)
print(pen2, pen == pen2, pen == Product("Pen", 1.5))
try:
Line(book, 0)
except ValueError as e:
print("ValueError:", e)
Order(customer='Rina', lines=[Line(product=Product(name='Pen', price=1.5), qty=4), Line(product=Product(name='Book', price=12.0), qty=1)])
18.0
{'product': {'name': 'Pen', 'price': 1.5}, 'qty': 4}
Product(name='Pen', price=1.75) False True
ValueError: qty must be at least 1
| Feature | Where |
|---|---|
frozen=True |
a Product cannot change by accident |
__post_init__ |
validates qty |
field(default_factory=list) |
each Order has its own list |
@property |
totals computed from the fields |
asdict, replace |
convert to a dictionary and copy with a change |
The products and prices are made up.
Common mistakes
- A mutable default (
items: list = []): usedefault_factory. - A field without a default after one with a default.
- Forgetting the type annotation. A name without an annotation is a class attribute, not a field.
- Expecting the annotations to be enforced.
- Mutating a frozen object (use
replacefor a changed copy). - Hashing a mutable dataclass (it is unhashable unless frozen).
- Putting a dataclass in a set or as a key and then changing it.
Key takeaways
@dataclasswrites__init__,__repr__and__eq__from annotated fields.- Use
field(default_factory=list)for mutable defaults. frozen=Truegives immutable, hashable objects;order=Truegives comparisons and sorting.__post_init__validates or computes fields;asdict,astupleandreplaceconvert and copy.- Dataclasses are ordinary classes: add methods and properties freely.
Practice
1. Write a dataclass Book with title: str and pages: int = 100.
Show answer
@dataclass
class Book:
title: str
pages: int = 100
2. Why is tags: list = [] rejected?
Show answer
One list would be shared by all objects. Use tags: list = field(default_factory=list).
3. How do you make a dataclass usable as a dictionary key?
Show answer
Use @dataclass(frozen=True), which makes it immutable and gives it a __hash__.
4. How do you get a copy of a frozen object with one field changed?
Show answer
dataclasses.replace(obj, field=new_value).
5. Where do you check that a field is not negative?
Show answer
In __post_init__, raising ValueError if the value is invalid.
6. What decides the sort order with order=True?
Show answer
The fields are compared in the order they are declared in the class, like a tuple.