Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Data Structures and Functional Tools

The dataclasses module

Reference for Python's dataclasses module: @dataclass options, field(), defaults, frozen and slots, __post_init__, replace(), asdict() and common pitfalls.

The dataclasses module writes the boring parts of a class for you. You declare fields with type annotations, add the @dataclass decorator, and Python generates __init__, __repr__ and __eq__ (and optionally ordering, hashing and immutability) from those annotations.

Use a data class for objects that mostly hold values: points, settings, records, messages. The annotations are not enforced at runtime; they only tell the decorator which names are fields and are available to type checkers.

Python
from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float = 0.0

Try it

Python Fields, defaults and post-init

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python frozen, order, slots, replace and asdict

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
@dataclass
@dataclass(init=True, repr=True, eq=True, order=False,
           unsafe_hash=False, frozen=False, match_args=True,
           kw_only=False, slots=False)
Option Description
init Generate __init__() from the fields.
repr Generate __repr__() such as Point(x=1, y=2).
eq Generate __eq__() that compares the fields as a tuple (only between instances of the same class).
order Generate <, <=, >, >= comparing fields in order. Needs eq=True.
frozen Make instances read-only; assignment raises FrozenInstanceError. Also makes the class hashable when eq=True.
unsafe_hash Force a __hash__() even for a mutable class. Rarely a good idea.
slots Create __slots__ for lower memory use and no per-instance __dict__ (3.10).
kw_only Make every field keyword-only (3.10).
match_args Set __match_args__ so instances work in positional match patterns (3.10).

Helpers: field(), fields(), asdict(), astuple(), replace(), is_dataclass(), make_dataclass(), KW_ONLY and InitVar.

field() parameters: default, default_factory, init, repr, eq, compare, hash, kw_only and metadata.

Raises: TypeError when a required argument is missing or a field without a default follows one with a default; ValueError for a mutable default such as []; FrozenInstanceError (a subclass of AttributeError) when assigning to a frozen instance.

Usage notes

  • Mutable defaults are rejected. tags: list = [] raises ValueError. Use field(default_factory=list).
  • Field order matters. Fields without defaults must come before fields with defaults, unless you use kw_only=True or the KW_ONLY sentinel.
  • __post_init__ runs right after __init__ and is the place for validation and derived fields. Fields declared with init=False are not set by __init__, so assign them there.
  • InitVar fields are passed to __init__ and __post_init__ but are not stored as attributes.
  • Annotations are not checked. Item("pen", "cheap") succeeds; use a type checker or validate in __post_init__.
  • frozen=True is shallow. A frozen class holding a list can still have that list modified.
  • eq=True with frozen=False sets __hash__ to None: such instances cannot be dictionary keys or set members. Freeze the class if you need hashing.
  • replace(obj, field=value) returns a new shallow copy with some fields changed. It calls __init__, so init=False fields cannot be replaced.
  • asdict() and astuple() recurse into nested data classes, lists, tuples and dictionaries, and deep-copy other values.
  • Inheritance collects fields from base classes in order; a subclass redefining a field keeps its original position.
  • Compared with namedtuple: data classes are mutable by default, support defaults, methods and inheritance naturally, and are not tuples.
  • Compared with typing.NamedTuple: use NamedTuple when you need tuple behavior (unpacking, indexing) and immutability.