Python Reference ยท Classes and Special Methods
Dataclasses overview
Concept guide to Python dataclasses: the @dataclass decorator, field(), defaults, frozen and ordered options, __post_init__, slots and asdict.
The @dataclass decorator from the dataclasses module (Python 3.7+) writes the boring parts of a class for you. You list the fields with type annotations, and it generates __init__(), __repr__() and __eq__(). Options add ordering, immutability, hashing and __slots__.
The annotations are used only to find the fields; Python does not enforce the types. Use a dataclass whenever a class mainly holds values, such as a point, a configuration or a row from a table.
The basics
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.
Fields with defaults must come after fields without. A mutable default such as [] is rejected; wrap it in field(default_factory=list) so each instance gets its own list.
Options
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.
Key rules
- Decorator arguments:
eq=True(default),order=Trueadds<,<=,>,>=comparing fields as tuples,frozen=Trueblocks assignment and makes the class hashable,slots=True(3.10+) saves memory,kw_only=True(3.10+) makes all parameters keyword-only,repr,initandunsafe_hashswitch parts on or off. field()controls one field:default,default_factory,init=False,repr=False,compare=False,kw_only=True,metadata.__post_init__runs after the generated__init__; use it for validation and derived values.InitVarmarks an init-only parameter that is passed to__post_init__but not stored.- Helpers:
asdict()andastuple()convert (recursively),replace()makes a modified copy,fields()lists fields,is_dataclass()tests. - Inheritance works; fields of base classes come first. A defaulted base field forces later fields to have defaults unless
kw_onlyis used. - Equality compares fields only if both objects have exactly the same class.
- Unhashable by default. With
eq=Trueand not frozen,__hash__is set toNone, so instances cannot be set members or dict keys. - Alternatives:
typing.NamedTuplefor immutable tuples,attrsor Pydantic when you need validation or conversion.