On this page
dataclasses.asdict
Up: dataclasses | Next: dataclasses.astuple
Rel: dataclasses.astuple, dataclasses.dataclass, dataclasses.field, dataclasses.Field
Ref: docs.python.org — dataclasses.asdict
Tags: #public #python3 #stdlib #dataclasses
Import
import dataclasses
from dataclasses import asdict
Signature & Overview
dataclasses.asdict(obj, *, dict_factory=<class 'dict'>)
Return the fields of a dataclass instance as a new dictionary mapping field names to field values.
Usage
from dataclasses import asdict, dataclass
@dataclass
class Tag:
name: str
@dataclass
class Post:
title: str
tags: list[Tag]
d = asdict(Post("Intro", [Tag("python")]))
assert d == {"title": "Intro", "tags": [{"name": "python"}]}
Gotchas
- Deep-copies everything:
asdict()recursively converts nested dataclasses, lists, dicts, and tuples and deep-copies values—for a fast shallow dict, use{f.name: getattr(obj, f.name) for f in fields(obj)}. - Instance only: Passing a dataclass class instead of an instance raises
TypeError.
REPL Inspect
from dataclasses import asdict
help(asdict)
Linked from
- tuts/python3/stdlib_module/dataclasses
- tuts/python3/stdlib_module/dataclasses/astuple
- tuts/python3/stdlib_module/dataclasses/dataclass
- tuts/python3/stdlib_module/dataclasses/field
- tuts/python3/stdlib_module/dataclasses/Field_class
- tuts/python3/stdlib_module/dataclasses/fields
- tuts/python3/stdlib_module/dataclasses/FrozenInstanceError
- tuts/python3/stdlib_module/dataclasses/InitVar
- tuts/python3/stdlib_module/dataclasses/is_dataclass
- tuts/python3/stdlib_module/dataclasses/make_dataclass
- tuts/python3/stdlib_module/dataclasses/replace
Related notes
- tuts/python3/stdlib_module/dataclasses/astuple Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/dataclass Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/field Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/Field_class Linked here; links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses/fields links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/FrozenInstanceError links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/InitVar links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/is_dataclass links to this page; shared tags: #dataclasses, #stdlib
- tuts/python3/stdlib_module/dataclasses/make_dataclass links to this page; shared tags: #dataclasses, #stdlib