Python Dataclasses
Many classes exist mainly to hold data: a point, a product, a user record. Writing them by hand means a lot of repetitive code — an __init__ that copies every argument to self, a __repr__ for debugging, an __eq__ for comparisons. The dataclasses module (Python 3.7+) writes all of that for you.
Before and after
The hand-written version:
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}, quantity={self.quantity!r})"
def __eq__(self, other):
return (self.name, self.price, self.quantity) == (other.name, other.price, other.quantity)The dataclass version:
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
def total_value(self):
return self.price * self.quantity
p = Product("Keyboard", 45.0, 3)
print(p)
print(p.total_value())
print(p == Product("Keyboard", 45.0, 3))
print(Product("Mouse", 12.5))Product(name='Keyboard', price=45.0, quantity=3)
135.0
True
Product(name='Mouse', price=12.5, quantity=0)
Each field is declared with a type annotation (name: str). The @dataclass decorator reads them and generates __init__, __repr__ and __eq__. You can still add normal methods.
Note: The annotations are documentation; Python doesn't enforce them at runtime.
Product(1, "x")would be accepted.
Default values and field()
Fields with defaults must come after fields without. For mutable defaults such as lists, use field(default_factory=...) so every instance gets its own fresh list:
from dataclasses import dataclass, field
@dataclass
class Order:
customer: str
items: list = field(default_factory=list)
shipped: bool = False
a = Order("Kim")
b = Order("Long")
a.items.append("book")
print(a)
print(b)Order(customer='Kim', items=['book'], shipped=False)
Order(customer='Long', items=[], shipped=False)
Writing items: list = [] would raise a ValueError — the dataclass module protects you from the shared-mutable-default bug.
Options of @dataclass
| Option | Effect |
|---|---|
order=True |
generates <, <=, >, >= comparing fields in order |
frozen=True |
instances are immutable (and hashable) |
slots=True |
uses __slots__ for less memory (Python 3.10+) |
kw_only=True |
all fields must be passed by keyword (Python 3.10+) |
Ordering
from dataclasses import dataclass
@dataclass(order=True)
class Version:
major: int
minor: int
patch: int = 0
versions = [Version(2, 1), Version(1, 9, 3), Version(2, 0, 7)]
print(sorted(versions))
print(max(versions))
print(Version(1, 2) < Version(1, 10))[Version(major=1, minor=9, patch=3), Version(major=2, minor=0, patch=7), Version(major=2, minor=1, patch=0)]
Version(major=2, minor=1, patch=0)
True
Frozen dataclasses
from dataclasses import dataclass, FrozenInstanceError, replace
@dataclass(frozen=True)
class Point:
x: int
y: int
p = Point(1, 2)
try:
p.x = 10
except FrozenInstanceError:
print("Point is immutable")
moved = replace(p, x=10) # make a modified copy instead
print(p, moved)
print({p: "start", moved: "end"}[moved]) # frozen -> usable as dict keyPoint is immutable
Point(x=1, y=2) Point(x=10, y=2)
end
__post_init__ and helpers
If you need validation or derived fields, define __post_init__; it runs right after the generated __init__. The helpers asdict() and astuple() convert an instance into plain data — handy for JSON:
from dataclasses import dataclass, field, asdict
@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width <= 0 or self.height <= 0:
raise ValueError("sides must be positive")
self.area = self.width * self.height
r = Rectangle(3, 4)
print(r)
print(asdict(r))
try:
Rectangle(-1, 2)
except ValueError as err:
print("ValueError:", err)Rectangle(width=3, height=4, area=12)
{'width': 3, 'height': 4, 'area': 12}
ValueError: sides must be positive
field(init=False) keeps area out of the constructor's parameters.
Tip: Reach for a dataclass whenever you'd otherwise pass around a dict with fixed keys. You get attribute access, a readable printout, equality and editor autocompletion for free.
Test yourself
Which methods does @dataclass generate by default?
- __init__, __repr__ and __eq__
- Only __init__
- __init__, __hash__ and __lt__
- __str__ and __len__
How should you give a dataclass field an empty list as its default?
- items: list = []
- items: list = list
- items: list = field(default_factory=list)
- items: list = None only
What does frozen=True do?
- Makes instances faster
- Prevents attributes from being changed after creation
- Disables __repr__
- Sorts the fields