Home

dataclasses

Dataclasses are a Python feature provided by the dataclasses module that simplify the creation of classes whose primary purpose is to store data. Introduced in Python 3.7 (PEP 557), they reduce boilerplate by automatically generating common methods. When a class is decorated with @dataclass and its fields are annotated with types, Python generates an __init__, __repr__, and __eq__ methods by default, and can also generate ordering methods if requested.

Fields in a dataclass are defined with type annotations. You can assign default values or use default_factory

Special markers include InitVar, used for constructor parameters that are not stored as attributes, and ClassVar,

Post-initialization and utilities: __post_init__ is invoked after the generated __init__ to perform extra initialization. In frozen

for
fields
that
require
a
mutable
default,
such
as
lists
or
dicts.
The
dataclass
decorator
accepts
several
options,
including
init,repr,
eq,
order,
and
frozen,
which
control
whether
the
corresponding
methods
are
generated
and
whether
instances
are
immutable.
The
field()
function
provides
per-field
customization,
including
default
values,
default_factory,
whether
a
field
participates
in
__init__,
and
metadata
attached
to
the
field.
which
marks
class-level
data
that
should
be
ignored
by
dataclass-generated
methods.
dataclasses,
attributes
cannot
be
assigned
after
creation,
though
object.__setattr__
can
be
used
within
__post_init__
if
necessary.
The
module
also
provides
asdict
and
astuple
to
convert
dataclass
instances
to
dicts
or
tuples,
and
replace
to
create
a
new
instance
with
some
fields
updated.
Dataclasses
are
well
suited
for
simple
data
containers
and
can
be
less
verbose
than
manually
writing
boilerplate
code.