Sub topic 10
Converting and copying: asdict, astuple, replace, fields
What this chapter assumes
You should know how to declare a dataclass with @dataclass, how defaults and field(default_factory=...) work, and what __post_init__ and InitVar do. You should also know the difference between a shallow copy and a deep copy.
This chapter covers four functions from the dataclasses module. They convert an instance to plain Python data, make a modified copy, and describe a class's fields.
The four helpers at a glance
| Function | Input | Returns | Copies values? |
|---|---|---|---|
| `fields(obj_or_cls)` | Class or instance | Tuple of `Field` objects | No, it describes the schema |
| `asdict(obj)` | Instance only | `dict` of field names to values | Yes, recursively |
| `astuple(obj)` | Instance only | `tuple` of field values | Yes, recursively |
| `replace(obj, **changes)` | Instance only | New instance of the same class | No, it is shallow |
All four work from the same source. The decorator records each field in the class's __dataclass_fields__ attribute, and the helpers read that record.
fields(): inspecting the schema
fields() returns a tuple of Field objects, one for each field in definition order. You can pass the class or an instance. Pseudo-fields such as InitVar and ClassVar annotations are not included.
from dataclasses import dataclass, field, fields, MISSING
@dataclass
class Item:
name: str
qty: int = 1
tags: list[str] = field(default_factory=list, metadata={"unit": "labels"})
for f in fields(Item):
print(f.name, f.type, f.default is MISSING, f.default_factory is MISSING)
print(fields(Item)[2].metadata["unit"]) # labelsThis prints:
name <class 'str'> True True
qty <class 'int'> False True
tags list[str] True FalseThe MISSING sentinel means "not provided". A field with neither a default nor a factory has MISSING in both attributes, so the constructor requires it. A Field also exposes init, repr, compare, hash, kw_only and metadata. The metadata mapping is read-only, and the dataclass machinery never uses it. It is a place for your own code to attach hints such as units, validation rules or serialization names.
fields() raises TypeError for objects that are not dataclasses. To test first, use dataclasses.is_dataclass(obj). It returns True for both dataclass classes and their instances. To distinguish them, add not isinstance(obj, type).
asdict and astuple
asdict() builds a dictionary from the instance's fields. astuple() builds a tuple in field order. Both recurse. A field that holds another dataclass is converted too, and so are dataclasses inside lists, tuples and dicts.
from dataclasses import dataclass, asdict, astuple
@dataclass
class Address:
city: str
zip_code: str
@dataclass
class Person:
name: str
address: Address
phones: list[str]
p = Person("Ana", Address("Lisbon", "1000"), ["111", "222"])
d = asdict(p)
print(d)
# {'name': 'Ana', 'address': {'city': 'Lisbon', 'zip_code': '1000'}, 'phones': ['111', '222']}
d["phones"].append("333")
print(p.phones) # ['111', '222'] (the original is untouched)
print(astuple(p))
# ('Ana', ('Lisbon', '1000'), ['111', '222'])The nested Address became a dict in the first result and a tuple in the second. The phones list stays a list, but it is a new list.
What gets copied
Values that are not dataclasses, lists, tuples or dicts are copied with copy.deepcopy(). That is why changing d["phones"] did not affect p. It also has costs:
- Large or deeply nested data makes
asdict()slow, because it copies everything. - An object that cannot be deep-copied, such as a lock or an open file, raises an error.
- Two references to the same object in the source become two separate objects in the result.
What gets included
asdict() and astuple() include every entry from fields(). That means fields with repr=False or compare=False are included, and fields with init=False are included. InitVar values are not included, because they were never stored. Plain attributes you assigned without an annotation are not included either.
A shallow alternative
When you only need the top level, or you want to keep the original objects, build the dict yourself:
from dataclasses import fields
def shallow_asdict(obj):
return {f.name: getattr(obj, f.name) for f in fields(obj)}
print(shallow_asdict(p))
# {'name': 'Ana', 'address': Address(city='Lisbon', zip_code='1000'), 'phones': ['111', '222']}Here address is still an Address object, and phones is the same list object that p holds.
Customizing the output with dict_factory
asdict() accepts a dict_factory argument. It is called with a list of (name, value) pairs once for each dataclass it converts, including nested ones. This example drops None values at every level:
from dataclasses import dataclass, asdict
from typing import Optional
@dataclass
class Profile:
name: str
nickname: Optional[str] = None
@dataclass
class Account:
id: int
profile: Profile
note: Optional[str] = None
def drop_none(pairs):
return {k: v for k, v in pairs if v is not None}
acc = Account(7, Profile("Ana"))
print(asdict(acc)) # {'id': 7, 'profile': {'name': 'Ana', 'nickname': None}, 'note': None}
print(asdict(acc, dict_factory=drop_none)) # {'id': 7, 'profile': {'name': 'Ana'}}astuple() has the matching tuple_factory argument. It is rarely needed.
Going back: dict to instance
There is no built-in inverse. For flat dataclasses, unpack the dict:
@dataclass
class Point:
x: int
y: int
print(Point(**{"x": 1, "y": 2})) # Point(x=1, y=2)This does not rebuild nested dataclasses. After asdict(p), Person(**d) leaves address as a plain dict. You must convert nested values yourself, or use a library that reads the type annotations.
replace: modified copies
replace(obj, **changes) creates a new instance of the same class. It takes every field value from obj, applies your changes, and calls the class constructor. This is the normal way to "modify" a frozen dataclass.
from dataclasses import dataclass, replace
@dataclass(frozen=True)
class Settings:
host: str
port: int = 8080
debug: bool = False
base = Settings("localhost")
dev = replace(base, debug=True)
print(base) # Settings(host='localhost', port=8080, debug=False)
print(dev) # Settings(host='localhost', port=8080, debug=True)
print(base is dev) # FalseBecause replace() goes through __init__, it has these consequences:
__post_init__runs again, so validation and derived values are recomputed.- Fields declared with
init=Falsecannot be passed toreplace(). Their values are not copied from the source either. They are rebuilt by__post_init__or take their default. - An
InitVarwithout a default must be supplied, because its value was not stored on the instance. - Passing an unknown field name raises
TypeError.
from dataclasses import dataclass, field, replace
@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("width and height must be non-negative")
self.area = self.width * self.height
r = Rectangle(3, 4)
wide = replace(r, width=10)
print(wide.area) # 40
try:
replace(r, area=1)
except ValueError as e:
print(e) # field area is declared with init=False, it cannot be specified with replace()The derived area is correct in the copy because __post_init__ ran again. This is the main reason to prefer replace() over copying an instance and then assigning to its attributes.
replace is shallow
The new instance holds the same objects as the old one. For mutable fields, both instances now share them:
from dataclasses import dataclass, field, replace
import copy
@dataclass
class Basket:
items: list[str] = field(default_factory=list)
a = Basket(["x"])
b = replace(a)
b.items.append("y")
print(a.items) # ['x', 'y'] (shared list)
c = replace(a, items=list(a.items)) # copy only the field that matters
d = copy.deepcopy(a) # or copy everythingPass a fresh copy of each mutable field you plan to change, or use copy.deepcopy() on the whole instance.
Choosing a helper
| You want to... | Use |
|---|---|
| Write generic code such as a serializer or a table printer | `fields()` |
| Send data to JSON, a database row or a template | `asdict()` |
| Unpack values positionally or use them as a sort key | `astuple()` |
| Change one value on a frozen instance | `replace()` |
| Copy a dataclass whose fields contain mutable data | `copy.deepcopy()` |
| Convert a large object quickly, keeping nested objects | A hand-written loop over `fields()` |
Common errors
TypeError: asdict() should be called on dataclass instancesappears when you pass a class instead of an instance.fields()accepts both, butasdict(),astuple()andreplace()do not accept a class.ValueError: field x is declared with init=False, it cannot be specified with replace()means you tried to set a computed field. Change the inputs it is computed from.ValueError: InitVar 'password' must be specified with replace()means the class has anInitVarwith no default. Pass it again.- A "copy" that changes the original is almost always the shallow behavior of
replace()with a shared list or dict.
Exercise
A dataclass Order has fields id: int and lines: list[str] (default_factory=list). You run o2 = replace(o1, id=2) and then o2.lines.append("tea"). What does o1.lines contain, and how do you change the code so that o1 is unaffected?
Show answer
o1.lines also contains "tea", because replace() is shallow and both instances hold the same list. Use replace(o1, id=2, lines=list(o1.lines)), or copy.deepcopy(o1) followed by setting id, so o2 gets its own list.
Exercise
Write a function to_row(obj) that returns a list of (field_name, value) pairs for a dataclass instance. It must skip fields whose repr is False and must not deep-copy nested objects. Which helper do you build it on, and why not asdict()?
Show answer
Build it on fields(): [(f.name, getattr(obj, f.name)) for f in fields(obj) if f.repr]. asdict() includes repr=False fields, has no option to skip them, and deep-copies every value.