Home

dataclass

Dataclass is a Python construct that provides a decorator and helper functions for creating classes intended primarily for storing data. It automates common boilerplate tasks by generating methods such as __init__, __repr__, and __eq__, and, if requested, ordering methods. Introduced in Python 3.7 as part of the dataclasses module, it can also be backported to earlier versions via a separate package.

Usage: declare a class with type-annotated attributes and apply @dataclass. Fields with defaults must follow non-default

Dataclasses provide helpful utilities such as asdict() and astuple() to convert instances to dictionaries or tuples,

Limitations: dataclasses rely on type annotations and simple storage patterns; they are not a full object system

fields.
Default
values
are
shared
across
instances,
so
use
default_factory
for
mutable
types
like
list
or
dict.
Per-field
behavior
can
be
customized
with
field(),
which
can
set
default,
default_factory,
init,
repr,
compare,
metadata,
or
exclude
a
field
from
certain
generated
methods.
Class-level
options
include
init,
repr,
eq,
order,
frozen,
and
post-init
validation
via
__post_init__.
and
replace()
to
create
a
copy
with
some
fields
altered.
They
pair
well
with
type
hints
and
support
inheritance.
replacement.
Complex
invariants
should
be
enforced
in
__post_init__,
and
mutable
fields
require
careful
handling
to
avoid
shared
state.
Although
frozen
dataclasses
prevent
attribute
reassignment,
they
can
still
contain
mutable
objects
that
may
be
modified
in
place.