Skip to content
Tutorials Center
My learning

Topics

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

Python What @dataclass generates

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

Python frozen, order 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.

Key rules

  • Decorator arguments: eq=True (default), order=True adds <, <=, >, >= comparing fields as tuples, frozen=True blocks assignment and makes the class hashable, slots=True (3.10+) saves memory, kw_only=True (3.10+) makes all parameters keyword-only, repr, init and unsafe_hash switch 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.
  • InitVar marks an init-only parameter that is passed to __post_init__ but not stored.
  • Helpers: asdict() and astuple() 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_only is used.
  • Equality compares fields only if both objects have exactly the same class.
  • Unhashable by default. With eq=True and not frozen, __hash__ is set to None, so instances cannot be set members or dict keys.
  • Alternatives: typing.NamedTuple for immutable tuples, attrs or Pydantic when you need validation or conversion.