Request and response records
Represent validated or transported application data with less handwritten initialization and representation code.
Python · Module
The dataclasses module generates common methods for classes whose fields are declared with type annotations. Its decorator and helper functions support initialization, comparison, immutability, conversion, inspection, and dynamic class creation.
The dataclasses module turns annotated classes into data-focused classes by generating methods such as initialization and representation. The decorator inspects annotated fields, while options control comparison, ordering, immutability, slots, keyword-only initialization, and other generated behavior.
@dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, **kwargs)| Name | Type | Description |
|---|---|---|
cls | type | None | Class to decorate; annotated attributes define its fields. |
init | bool | Generate an __init__ method. |
repr | bool | Generate a __repr__ method. |
eq | bool | Generate equality methods. |
order | bool | Generate ordering methods. |
unsafe_hash | bool | Generate a hash method according to the documented rules. |
frozen | bool | Prevent ordinary field assignment and deletion after initialization. |
match_args | bool | Create __match_args__ for positional pattern matching. |
kw_only | bool | Make fields keyword-only in the generated initializer. |
slots | bool | Generate __slots__. |
weakref_slot | bool | Generate a weak-reference slot. |
The @dataclass decorator returns the class it was applied to. fields() returns a tuple of Field objects; asdict() and astuple() return converted representations; is_dataclass() returns a boolean.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class User:
name: str
roles: list[str] = field(default_factory=list)
user = User("Ada")
print(user)
print(user.roles)The decorator generates initialization and representation behavior from annotated fields; frozen=True prevents attribute reassignment, while default_factory creates a fresh list for each instance.
Represent validated or transported application data with less handwritten initialization and representation code.
Model configuration or domain values where equality and readable representations are useful.
Create immutable, hashable-style records when the documented equality and frozen settings are appropriate.
Convert nested dataclass instances into dictionaries or tuples for serialization boundaries.
@dataclass examines annotated class variables and uses them as fields. It can then generate methods such as __init__() and __repr__() for the class.
Follow-up: How would you define a mutable default collection? Use field(default_factory=list) so each instance receives a separate list.
A field() specification supplies per-field options such as a default, a default factory, whether it participates in initialization, representation, comparison, or pattern matching. A factory is called when a new instance needs that field's value.
Follow-up: Why prefer default_factory over a list literal? A literal would be one class-level default object, while the factory creates a new value per instance.
frozen=True adds behavior that prevents ordinary field reassignment and deletion after construction. It does not make referenced mutable objects deeply immutable.
Follow-up: Does frozen=True automatically make an instance hashable? Hash generation also depends on eq and unsafe_hash settings, so inspect the documented rules rather than assuming it.
dataclassfieldfieldsasdictastuplereplacemake_dataclassis_dataclass