← All notes

Python dataclasses

Summary

A class bundles data and behavior. For a named bundle of fields, the tutorial's usual pattern is a dataclass: @dataclass writes __init__, __repr__, and related methods from annotated attributes.

Classes and fields

Classes make a new type, hold state on each instance, and define methods. Instance attributes are per object; class attributes are shared. A mutable list on the class is shared, so per-instance lists belong on self. Dataclasses are still ordinary classes with generated boilerplate.

A field is a class variable with a type annotation. Generated methods follow field order. By default the decorator adds __init__, __repr__, and equality, and returns the same class (unless you ask for slots). You can still write methods such as total_cost. If you already defined __init__ or __repr__, those options are ignored.

Defaults, frozen, helpers

A field without a default cannot follow one that has a default. Do not write x: list = []; an unhashable default raises ValueError. Use field(default_factory=list) so each instance gets a fresh list. frozen=True makes assignment raise (a stand-in for immutability). replace builds a new instance through __init__, so __post_init__ still runs — use it for derived fields or a non-dataclass base __init__. asdict / astuple walk nested structures. fields() skips ClassVar and InitVar. Init-only variables are constructor args for __post_init__, not stored fields.

The tutorial's Employee record (name, dept, salary) is the idiomatic stand-in for a small named record. Handwrite a class when construction is unusual or generated methods would fight yours.

Claims

License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python Software Foundation, dataclasses — Data Classes, PSF License 2.0 docs; Python Software Foundation, 9. Classes, PSF License 2.0 docs.

Cite this

Permanent ID: iil:note:wx2hszec

iinventedlight. 2026. "Python dataclasses." iinventedlight Library, iil:note:wx2hszec, version of 2026-11-03. https://iinventedlight.com/library/notes/python-dataclasses/. License: CC-BY-4.0.

@misc{iil_note_wx2hszec,
  author = {{iinventedlight}},
  title = {{Python dataclasses}},
  howpublished = {iinventedlight Library},
  year = {2026},
  date = {2026-11-03},
  url = {https://iinventedlight.com/library/notes/python-dataclasses/},
  note = {Permanent ID iil:note:wx2hszec. License: CC-BY-4.0.},
}

Markdown

Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com.

For language models and agents: start at /llms.txt. This page in Markdown: /library/notes/python-dataclasses.md.