Sub topic 12
Less boilerplate with dataclasses
This chapter assumes you can write a class with __init__, __repr__, and __eq__, and that you know the difference between instance and class attributes. It also assumes you have seen the mutable class attribute bug from earlier in this tutorial. Dataclasses automate the repetitive parts of those classes.
The problem dataclasses solve
A class that mainly holds data needs the same three methods every time. You write __init__ to copy arguments into attributes. You write __repr__ so printing is readable. You write __eq__ to compare by value.
class PlainOrder:
def __init__(self, order_id, items=None, paid=False):
self.order_id = order_id
self.items = list(items or [])
self.paid = paid
def __repr__(self):
return f"PlainOrder(order_id={self.order_id!r}, items={self.items!r}, paid={self.paid!r})"
def __eq__(self, other):
if not isinstance(other, PlainOrder):
return NotImplemented
return (self.order_id, self.items, self.paid) == (other.order_id, other.items, other.paid)
print(PlainOrder(1))Adding a field means editing three places, and forgetting one causes quiet bugs. The dataclasses module in the standard library generates these methods from a list of annotated fields.
A first dataclass
Decorate a class with @dataclass and declare fields as class-level annotations.
from dataclasses import dataclass, field
@dataclass
class Order:
order_id: int
items: list[str] = field(default_factory=list)
paid: bool = False
o = Order(1)
o.items.append("book")
print(o) # Order(order_id=1, items=['book'], paid=False)
print(Order(1) == Order(1)) # TrueThe decorator reads __annotations__ and writes __init__, __repr__, and __eq__ into the class. The annotation is required: a plain x = 5 without an annotation creates an ordinary class attribute, not a field. Python does not enforce the annotated types at runtime. Order("abc") works. The annotations are there for readers and for type checkers.
Defaults and `default_factory`
A field without a default is required. A field with a default is optional. Fields without defaults must come before fields with defaults, because the generated __init__ uses the same ordering rule as ordinary functions.
from dataclasses import dataclass
@dataclass
class Bad:
name: str = "x"
age: int # TypeError: non-default argument 'age' follows default argumentMutable defaults need special care. This is the shared class attribute bug in a new form, and dataclasses reject the obvious version:
from dataclasses import dataclass
try:
@dataclass
class Broken:
items: list = []
except ValueError as exc:
print(exc) # mutable default <class 'list'> for field items is not allowed: use default_factoryUse field(default_factory=list) instead. The factory is called once per instance, so each object gets its own list. Any zero-argument callable works: dict, set, or your own function.
Customizing fields with `field()`
The field() function controls how one field behaves.
| Argument | Effect |
|---|---|
| `default` | Plain default value |
| `default_factory` | Callable that builds a fresh default per instance |
| `repr=False` | Leave the field out of `__repr__` |
| `compare=False` | Leave the field out of `__eq__` and ordering |
| `init=False` | Leave the field out of `__init__` |
| `kw_only=True` | Make the field keyword-only in `__init__` (Python 3.10+) |
from dataclasses import dataclass, field
@dataclass
class User:
username: str
password: str = field(repr=False)
login_count: int = field(default=0, compare=False)
u = User("ana", "s3cret")
print(u) # User(username='ana', login_count=0)
print(u == User("ana", "s3cret", 5)) # TrueHiding password from repr keeps it out of logs and tracebacks that print the object. Excluding login_count from comparison means two users with the same credentials are equal even if their counters differ.
Decorator options
@dataclass accepts keyword arguments that change what it generates.
order=Trueadds__lt__,__le__,__gt__, and__ge__. They compare fields as tuples, in declaration order.frozen=Truemakes instances immutable. Assigning to a field raisesFrozenInstanceError.slots=True(Python 3.10+) generates__slots__, which reduces per-instance memory.kw_only=True(Python 3.10+) makes every field keyword-only.eq=Falseandrepr=Falseskip generating those methods.
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True, order=True)
class Version:
major: int
minor: int = 0
v1, v2 = Version(1, 2), Version(1, 10)
print(v1 < v2) # True
try:
v1.major = 2
except FrozenInstanceError as exc:
print("blocked:", exc)Equality and hashing
Ordinary classes are hashable by identity. A dataclass changes that, and the result depends on two options.
| `eq` | `frozen` | Result for `__hash__` |
|---|---|---|
| `True` (default) | `False` (default) | Set to `None`: instances are unhashable |
| `True` | `True` | Generated from the fields: instances are hashable |
| `False` | any | Inherited from `object` |
The first row surprises people. A default dataclass cannot be a dictionary key or a set member, because it is mutable and compares by value, so a hash could change while the object sits in a set. If you need hashing, use frozen=True.
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
try:
{Point(1, 2)}
except TypeError as exc:
print(exc) # unhashable type: 'Point'Post-init processing
The generated __init__ only assigns fields. For validation or derived values, define __post_init__, which the generated __init__ calls at the end.
from dataclasses import dataclass, field
@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) # Rectangle(width=3, height=4, area=12)The area field uses init=False, so callers cannot pass it. Note that area goes stale if you later change width. For a value that must always track other fields, a property from the previous chapter is the better tool.
With frozen=True, plain assignment in __post_init__ raises an error. Use object.__setattr__(self, "area", value) for derived fields in that case.
Inheritance between dataclasses
A dataclass can inherit from another dataclass. Fields are collected in order, starting from the base class.
from dataclasses import dataclass
@dataclass
class Animal:
name: str
@dataclass
class Dog(Animal):
tricks: int = 0
print(Dog("Rex", 2)) # Dog(name='Rex', tricks=2)The ordering rule can bite here. If the base class has a field with a default, every field in a subclass must also have one, unless you use kw_only=True. Keyword-only fields are exempt from the rule because they are not positional.
Helper functions
The module has functions that work on dataclass instances.
from dataclasses import dataclass, asdict, astuple, replace, fields
@dataclass
class Item:
name: str
price: float
item = Item("pen", 1.5)
print(asdict(item)) # {'name': 'pen', 'price': 1.5}
print(astuple(item)) # ('pen', 1.5)
print(replace(item, price=2.0)) # Item(name='pen', price=2.0)
print([f.name for f in fields(item)]) # ['name', 'price']replace builds a new instance with some fields changed. It is the usual way to "modify" a frozen instance. asdict and astuple recurse into nested dataclasses, lists, and dictionaries, and they copy the values, which can be slow for large structures.
When to use a dataclass
| Situation | Choice |
|---|---|
| Class mostly stores fields and needs value equality | Dataclass |
| Immutable, hashable record | `@dataclass(frozen=True)` |
| Class with significant behavior and custom construction | Ordinary class |
| Fixed-size record that behaves like a tuple | `typing.NamedTuple` |
| Dictionary-shaped data with a known set of keys | `TypedDict` |
A dataclass is still an ordinary class. You can add methods, properties, classmethods, and special methods to it. The decorator only saves you from writing the repetitive parts.
Common mistakes
- Forgetting the annotation, so the attribute is not a field and does not appear in
__init__or__repr__. - Using a mutable default directly instead of
default_factory. - Expecting runtime type checks. The annotations are not enforced.
- Putting a dataclass in a set or dictionary key without
frozen=True. - Calling
__post_init__assignments on a frozen class withoutobject.__setattr__. - Defining your own
__init__and expecting the decorator to keep it. The decorator does not overwrite a method defined in the class body for__repr__and__eq__, but for__init__the decorator will replace it unless you passinit=False.
Exercise
Write a dataclass Config with a required string field name, a list field tags that defaults to an empty list, and an integer retries that defaults to 3. Make it hashable. Explain why your design for tags needs special attention once the class is hashable.
Show answer
Use @dataclass(frozen=True) with name: str, tags: list[str] = field(default_factory=list), and retries: int = 3. Frozen plus the default eq=True makes __hash__ generated from the fields. The problem is that hash() includes tags, and a list is unhashable, so calling hash(Config("a")) raises TypeError. Frozen only blocks reassigning the field. It does not make the list immutable. A better design stores tags as a tuple: tags: tuple[str, ...] = (). A tuple default is immutable, so it needs no factory, and the instance is truly hashable.
Exercise
A dataclass Account has fields owner: str and balance: float = 0.0. You add limit: float after them. What happens, and how can you fix it without reordering?
Show answer
Defining the class raises TypeError: non-default argument 'limit' follows default argument, because the generated __init__ would have a required parameter after an optional one. Either give limit a default, move it before balance, or declare it with field(kw_only=True) (Python 3.10+), which takes it out of the positional ordering.