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.
from dataclasses import dataclass @dataclass class Point: x: float y: float = 0.0
Try it
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.
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
@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 = []raisesValueError. Usefield(default_factory=list). - Field order matters. Fields without defaults must come before fields with defaults, unless you use
kw_only=Trueor theKW_ONLYsentinel. __post_init__runs right after__init__and is the place for validation and derived fields. Fields declared withinit=Falseare not set by__init__, so assign them there.InitVarfields 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=Trueis shallow. A frozen class holding a list can still have that list modified.eq=Truewithfrozen=Falsesets__hash__toNone: 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__, soinit=Falsefields cannot be replaced.asdict()andastuple()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: useNamedTuplewhen you need tuple behavior (unpacking, indexing) and immutability.
Related
collections.namedtuple,typing,enum,copyclass,property- Lessons: Data classes, Classes, Special methods