Python Glossary Русский

Python 3.7+dataclassesfunction

dataclasses.asdict

conversion

Recursively convert a dataclass instance into a dict.

Syntax

dataclasses.asdict(obj, *, dict_factory=dict)

This is not a cheap view of __dict__: asdict walks nested dataclasses, lists, tuples and dicts recursively and deep-copies everything else, which costs real time on large structures. The result is not automatically JSON-ready either — datetime, Decimal, set and friends come back as themselves, and ClassVar/InitVar fields are excluded. When a flat copy of the attributes is enough, vars(obj) is far cheaper.

Examples

import dataclasses
@dataclasses.dataclass
class P:
    x: int
    y: int
print(dataclasses.asdict(P(1, 2)))   # → {'x': 1, 'y': 2}

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy