Home

asdict

asdict is a function from Python's standard library dataclasses module. It returns a dictionary representation of a dataclass instance by recursively converting its fields to dictionaries when appropriate. The function requires a dataclass instance and will raise a TypeError if given a non-dataclass object.

When applied to a dataclass, asdict includes each field in the output dictionary under its field name.

asdict is commonly used to prepare dataclass data for serialization, such as JSON encoding, since a dataclass

Some practical notes: asdict preserves a deep copy-like behavior for dataclass structures, producing new dicts and

If
a
field
value
is
itself
a
dataclass,
asdict
recursively
converts
it
to
a
dictionary.
If
a
field
is
a
list,
tuple,
or
dictionary,
its
contents
are
processed
recursively
as
well.
The
function
accepts
an
optional
dict_factory
argument
to
customize
the
type
of
dictionaries
created;
by
default
it
uses
the
built-in
dict.
instance
is
not
directly
JSON-serializable.
However,
it
does
not
guarantee
that
all
values
will
be
JSON
serializable;
non-serializable
objects
may
require
further
processing.
containers
rather
than
referencing
the
original
objects.
It
also
handles
recursive
references
to
avoid
infinite
loops
during
conversion.
The
function
is
part
of
Python
3.7
and
later.
There
is
a
related
concept
in
third-party
libraries
(for
example,
attrs
provides
a
similar
asdict)
but
the
standard
library
version
is
the
most
commonly
used
approach
for
native
dataclasses.