CKTIS / Python
dataclasses.asdict
Recursively converts a data-class instance into a dictionary of field names and values.
Version: Python 3.14; repository image, production runtime not attested
Syntax
dataclasses.asdict(obj, *, dict_factory=dict)Recursively converts a data-class instance into a dictionary of field names and values.
Nested data classes become nested dictionaries, and the converted mutable data can be changed separately.
Convert a dataclass instance to name/value mappings, applying dict_factory to converted dataclasses. Recursion follows nested dataclasses, dicts, lists and tuples and other values go through deepcopy. Passing the class instead of an instance raises TypeError. Updating the exported coordinate to 9 leaves the original Point at 3.
from dataclasses import asdict, dataclass
@dataclass
class Record:
values: list
r = Record([{"x": 1}])
d = asdict(r)
d["values"][0]["x"] = 2
assert r.values == [{"x": 1}]
try:
asdict(Record)
except TypeError:
pass
else:
raise AssertionError
Examples
import dataclasses
@dataclasses.dataclass
class Point:
x: int
@dataclasses.dataclass
class Row:
p: Point
r = Row(Point(3))
copy = dataclasses.asdict(r)
copy["p"]["x"] = 9
print(copy, r.p.x)
Result
{'p': {'x': 9}} 3Convert a dataclass instance to name/value mappings, applying dict_factory to converted dataclasses. Recursion follows nested dataclasses, dicts, lists and tuples and other values go through deepcopy. Passing the class instead of an instance raises TypeError. Updating the exported coordinate to 9 leaves the original Point at 3.