Sub topic 10
Converting and copying: asdict, astuple, replace, fields
This chapter assumes you can define a basic dataclass, know that @dataclass generates __init__, __repr__ and __eq__, and understand the difference between mutable and immutable objects. It covers four helper functions in the dataclasses module. They work on any dataclass instance, and none of them is a method on your class.
The four helpers at a glance
| Function | Input | Returns |
|---|---|---|
| `asdict(obj)` | instance | `dict` mapping field names to values |
| `astuple(obj)` | instance | `tuple` of field values in definition order |
| `replace(obj, **changes)` | instance | new instance with some fields changed |
| `fields(obj_or_cls)` | instance or class | tuple of `Field` objects |
Converting with asdict and astuple
asdict is the usual route to JSON, logging, or any API that expects plain dictionaries. astuple gives the values in the order the fields were declared.
from dataclasses import dataclass, asdict, astuple, replace, fields
@dataclass
class Point:
x: int
y: int
p = Point(1, 2)
print(asdict(p)) # {'x': 1, 'y': 2}
print(astuple(p)) # (1, 2)
print(replace(p, y=5)) # Point(x=1, y=5)
print([f.name for f in fields(p)]) # ['x', 'y']Both functions are recursive. If a field holds another dataclass, or a list, tuple or dict containing dataclasses, those are converted too. Other values are deep-copied.
from dataclasses import dataclass, asdict
@dataclass
class Address:
city: str
@dataclass
class Person:
name: str
addresses: list[Address]
person = Person("Ana", [Address("Lisbon"), Address("Porto")])
print(asdict(person))
# {'name': 'Ana', 'addresses': [{'city': 'Lisbon'}, {'city': 'Porto'}]}Copying with replace
replace creates a new instance of the same class with selected fields changed. The original is untouched, so it is the standard way to "modify" a frozen dataclass.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Settings:
host: str
port: int = 8080
old = Settings("localhost")
new = replace(old, port=9090)
print(old) # Settings(host='localhost', port=8080)
print(new) # Settings(host='localhost', port=9090)replace calls __init__ with the current values plus your changes. This has consequences:
__post_init__runs again, so validation and derived values are recomputed.- A field declared with
init=Falsecannot be passed toreplace. It raisesValueError. The field is recomputed by__post_init__instead. - An
InitVarwithout a default must be supplied again, orreplaceraisesTypeError. - The copy is shallow. A list field in the new instance is the same list object as in the old one.
Inspecting with fields
fields returns Field objects that describe each field. It accepts either an instance or the class. It does not include InitVar pseudo-fields.
from dataclasses import dataclass, field, fields
@dataclass
class Item:
name: str
tags: list[str] = field(default_factory=list, repr=False)
for f in fields(Item):
print(f.name, f.type, f.repr)
# name <class 'str'> True
# tags list[str] FalseUseful attributes of a Field are name, type, default, default_factory, init, repr, compare and metadata. A common use is writing generic code, such as a serializer that skips fields marked in metadata.
Common errors
- Calling
asdicton a class instead of an instance raisesTypeError. Pass an object, notPoint. - Passing a non-dataclass raises
TypeErrorin all four helpers. - Expecting
replaceto produce an independent copy of mutable fields. Copy them yourself if needed.
Exercise
A dataclass has a field area: float = field(init=False) computed in __post_init__. What happens when you call replace(obj, area=10.0), and how do you change the area?
Show answer
It raises ValueError, because replace does not accept fields with init=False. Change the inputs that area is computed from, for example replace(obj, width=5). The __post_init__ call then recomputes the area.
Exercise
Given @dataclass class Box: items: list[int], with a = Box([1]) and b = replace(a), does a.items is b.items hold? What about c = Box(**asdict(a))?
Show answer
For b, yes: replace is shallow, so both share one list. For c, no: asdict deep-copies the list, so c.items is a separate list.