The dataclasses module in the standard library writes the repetitive parts for you. One decorator on a class gives you an __init__, a __repr__, and an __eq__ that are all generated from the fields that you declare. That turns a data model from thirty lines of repetition into a handful of clear declarations.
The previous lesson in this module covered "__repr__ and __eq__: Objects That Print and Compare Well", and this lesson is the last one in the Python Classes and Objects module.
It arrived in Python 3.7, and it has been the standard answer to the question "I need a class that just holds some values" ever since. The key idea is that a dataclass is not a new kind of class. It is an ordinary class that gets a few dunder methods filled in for you at class creation time.
What does the dataclass decorator actually generate?
Decorate a class with @dataclass, list its annotated attributes, and you get a class with an __init__ that assigns each field, a __repr__ that prints every field, and an __eq__ that compares field by field. Your declarations become the source of truth, and the methods are generated from them.
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
stock: int
item = Product('keyboard', 79.5, 12)
print(item)
print(item.name, item.price)
print('equal?', item == Product('keyboard', 79.5, 12))
print('fields:', list(item.__dataclass_fields__.keys()))
Two details in that snippet matter. The annotations are not decoration, because they are how the decorator discovers which attributes are fields. An attribute without an annotation is not a field, and it does not get a parameter. The generated __init__ also takes the fields in the order that you declared them, so the order matters when you call it with positional arguments.
How do defaults work, and what about mutable ones?
A field with a plain default becomes an optional parameter. A mutable default, such as a list, a dictionary, or a set, is the same trap that you met with function arguments, because it is shared by every instance. The dataclasses module refuses to allow that, and it raises a ValueError at class definition time if you try.
from dataclasses import dataclass, field
@dataclass
class Cart:
owner: str
items: list = field(default_factory=list)
coupon: str = None
first = Cart('Asha')
second = Cart('Ben')
first.items.append('keyboard')
print('first :', first.items)
print('second:', second.items)
print('the lists are different objects:', first.items is not second.items)
The fix is field(default_factory=list). The factory is a callable that Python invokes once for every instance, and it produces a fresh empty list each time. Use default_factory=dict, default_factory=set, or any other callable that takes no arguments in exactly the same way.
There is also a default argument on the field() helper for the same purpose, and there is an init=False argument that marks a field as one which should not appear in the generated constructor. That is useful for a value that the class works out for itself.
What do frozen and order do?
@dataclass(frozen=True) makes the instances immutable. Any attempt to assign to a field after construction raises FrozenInstanceError. This is a strong guarantee and it is cheap, because you can pass the object around without worrying that somebody will change it. Being immutable also gives it a working __hash__ for free.
@dataclass(order=True) adds the comparison operators, so that instances can be sorted and compared with <. It needs the fields to be orderable, and it generates the operators in field declaration order, so put your main sort key first.
from dataclasses import dataclass, FrozenInstanceError
@dataclass(frozen=True)
class Point:
x: int
y: int
@dataclass(order=True)
class Job:
priority: int
label: str
p = Point(1, 2)
try:
p.x = 99
except FrozenInstanceError as exc:
print('FrozenInstanceError:', exc)
jobs = [Job(3, 'third'), Job(1, 'first'), Job(2, 'second')]
labels = []
for job in sorted(jobs):
labels.append(job.label)
print(labels)
There is one more option that is worth knowing, which is slots=True, available since Python 3.10. It generates a __slots__ attribute, which removes the per-instance __dict__. That makes instances smaller and a little faster to create, and it stops a typo from adding a stray attribute at runtime.
How do you validate or derive values after construction?
Define __post_init__, and the generated __init__ calls it once the fields have been assigned. That is the place for validation, and for computing derived values that you do not want callers to pass in.
from dataclasses import dataclass
@dataclass
class ServerConfig:
host: str = 'localhost'
port: int = 8080
def __post_init__(self):
if not 1 <= self.port <= 65535:
raise ValueError(f"port {self.port} is out of range")
print(ServerConfig())
print(ServerConfig('example.com', 443))
try:
ServerConfig(port=70000)
except ValueError as exc:
print('rejected:', exc)
For conversion, the module gives you asdict and astuple to turn an instance into a plain dictionary or a plain tuple, and it gives you replace to build a modified copy. replace is better than mutating, because it works with frozen dataclasses and because it goes through __post_init__ again, so the derived fields stay consistent.
There is one caveat about replace, and it is that it performs a shallow copy. A new instance is created and its fields are reassigned, but a mutable field such as a list is carried over by reference instead of being duplicated. The example below makes that visible, because editing the list on the copy also edits the list on the original.
from dataclasses import dataclass, field, asdict, astuple, replace
@dataclass
class ServerConfig:
host: str = 'localhost'
port: int = 8080
tags: list = field(default_factory=list)
config = ServerConfig(tags=['prod'])
print('asdict :', asdict(config))
print('astuple:', astuple(config))
updated = replace(config, port=9090)
print('original port:', config.port, '| copy port:', updated.port)
updated.tags.append('eu')
print('tags after editing the copy:', config.tags, updated.tags)
When should you skip the dataclass?
A dataclass is a great fit for a record with a handful of fields and simple behaviour. It is a poor fit when the class needs custom construction logic, when it holds a resource with a lifetime, or when the fields are computed rather than stored. If your __init__ needs to do real work, then write the class by hand, because at that point you are fighting the decorator instead of using it.
It is also worth knowing that a dataclass is a normal class underneath it. You can add methods, properties, and even non-field class attributes to it, and you can mix in behaviour from other classes as usual.
| You want | Reach for |
|---|---|
| a plain record with a few fields | @dataclass |
| the same thing but guaranteed to be immutable | @dataclass(frozen=True) |
| sortable records | @dataclass(order=True) |
| custom construction logic | a hand-written class |
| a type with a resource lifetime | a hand-written class with explicit setup and teardown |
Before you move on
- Annotate the fields that you want, and then decorate the class with
@dataclass. - Use
field(default_factory=list)for mutable defaults, and never a bare list. frozen=Truegives immutability and hashing,order=Truegives sorting, andslots=Truesaves memory.- Put validation and derived values in
__post_init__. - Use
asdict,astuple, andreplaceinstead of writing your own conversions.
Try it yourself: a config record with validation
Write a ServerConfig dataclass with host (default "localhost"), port (default 8080), tags (a list built with default_factory), and debug (default False). Validate in __post_init__ that the port is between 1 and 65535, and raise ValueError when it is not.
Then make a second dataclass called FrozenServerConfig with frozen=True, and confirm that assigning to a field raises an error. Add order=True to a third dataclass that holds a name and a port, build three of them, and sort them. Finish by using replace() to make a copy of a config with a different port, then edit the list of tags on the copy and check whether the list on the original changed as well. replace is a shallow copy, so it does. Build a genuinely independent copy with copy.deepcopy and confirm the difference.