How should I define a small record with dataclasses?
Quick answer
Use @dataclass when a small class mainly groups related, annotated values. Python’s dataclasses module can generate an initializer and a representation from those fields. Mark values that callers must provide without defaults, and give optional values defaults when appropriate. For a mutable default such as a list, use field(default_factory=...) so each instance gets a fresh list. Check that the syntax suits your target Python version. [S1]
The question, the details, the next step.
A practical checklist
Choose a class name that describes the record.
Annotate the related fields the record needs.
Separate required fields from fields with useful defaults.
Use a factory for mutable defaults such as lists.
Decide whether the record needs explicit behavior or validation.
Check compatibility with the Python version you target.
A few more useful answers
Does `@dataclass` create an initializer for the class?
By default, the dataclass decorator generates an initializer and a representation from the annotated fields. [S1]
Does `frozen=True` make every part of a record immutable?
No. It emulates read-only instances by raising on assignment, but the documentation says it does not make objects truly immutable. [S1]
Will this example work on every Python version?
Do not assume so. Check the dataclasses documentation and the syntax against the Python version you intend to use. [S1]
Sources
References used for this guide.
- [S1] Python dataclasses — official library reference docs.python.org · Checked
