Python Dataclasses: Declaring Data Classes Without Boilerplate
This article explains what the dataclass decorator generates from annotated fields, how defaults, frozen instances, ordering, slots and keyword-only fields work, and which limits the generated code has.
A class whose main purpose is to hold data requires, in plain Python, a constructor that assigns every attribute, a representation that shows them, and an equality method that compares them, and each of these methods repeats the same list of names. The module dataclasses, introduced in Python 3.7 (PEP 557), generates those methods from a list of annotated fields. The present article examines what the decorator @dataclass generates, how defaults and mutable values are declared, what the options frozen, order, slots and kw_only change, how instances are validated, copied and converted, and which limits the generated code has. A declaration of fields from which the boilerplate is derived is the secret weapon of this module.
From Boilerplate to Declaration
The decorator reads the annotated class attributes, in order, and turns each one into a field. From that list it writes __init__, __repr__ and __eq__, which would otherwise be written by hand and kept in step with every change of the fields.
from dataclasses import dataclass, fields
@dataclass
class Product:
name: str
price: float
quantity: int = 0
pen = Product("pen", 1.5)
print(pen) # Output: Product(name='pen', price=1.5, quantity=0)
print(pen == Product("pen", 1.5, 0)) # Output: True
print([f.name for f in fields(Product)]) # Output: ['name', 'price', 'quantity']
print(Product.__hash__) # Output: None
print(Product("pen", "free")) # Output: Product(name='pen', price='free', quantity=0)
The generated methods are ordinary methods of an ordinary class, which can receive further methods, properties and base classes like any other. Two lines deserve attention. The class is unhashable, because the decorator generates __eq__ and, for a mutable class, sets __hash__ to None, as the data model requires for objects whose equality may change. The last line shows that the annotations are not checked: @dataclass uses them only to find the fields, and a string is accepted as a price. Verifying those types is the task of a static checker, as discussed in the article devoted to advanced type hints.
Defaults and Mutable Values
A default value is written as an assignment in the class body, and fields with defaults must follow fields without them, as in a function signature. A mutable default, however, would be shared by every instance, which is a classic error with default arguments; the decorator therefore rejects any unhashable default and requires a factory instead.
from dataclasses import dataclass, field
try:
@dataclass
class Order:
items: list = []
except ValueError as error:
print(error) # Output (CPython 3.12): mutable default <class 'list'> for field items is not allowed: use default_factory
@dataclass
class Order:
customer: str
items: list[str] = field(default_factory=list)
first, second = Order("ada"), Order("grace")
first.items.append("pen")
print(first.items, second.items) # Output: ['pen'] []
The function field describes a field in more detail than a plain default: default_factory is called once per instance, init=False removes the field from the constructor, repr=False hides it from the representation, and compare=False excludes it from equality and ordering. Since Python 3.11, the check rejects every unhashable default, not only lists, dictionaries and sets.
Frozen Instances
With frozen=True, assignment to a field raises FrozenInstanceError, and the class receives a __hash__ derived from its fields, so its instances can be used as dictionary keys or set members. A modified copy is created with dataclasses.replace, or, since Python 3.13, with the generic function copy.replace.
from dataclasses import FrozenInstanceError, asdict, dataclass, replace
@dataclass(frozen=True)
class Money:
amount: int
currency: str = "EUR"
price = Money(100)
try:
price.amount = 90
except FrozenInstanceError as error:
print(error) # Output: cannot assign to field 'amount'
discounted = replace(price, amount=90)
print(discounted, price) # Output: Money(amount=90, currency='EUR') Money(amount=100, currency='EUR')
print(len({Money(100), Money(100), Money(5)})) # Output: 2
print(asdict(discounted)) # Output: {'amount': 90, 'currency': 'EUR'}
@dataclass(frozen=True)
class Basket:
items: list
basket = Basket([1])
basket.items.append(2)
print(basket) # Output: Basket(items=[1, 2])
try:
hash(basket)
except TypeError as error:
print(error) # Output: unhashable type: 'list'
A well-known science-fiction scene offers an exact image for a frozen instance: a smuggler is frozen in a block of carbonite, preserved intact and unable to move until the block is thawed. In the same way, a frozen dataclass keeps each of its fields bound to the same object for its whole life, and a change requires a new instance built with replace. The analogy, however, stops at this point, because the carbonite encases everything, whereas frozen protects only the bindings of the fields: the list inside Basket can still be modified, and a frozen instance that contains a list is not even hashable. Deep immutability requires immutable field types, such as tuples and frozenset. The function asdict converts an instance, recursively, into a dictionary, which is convenient for serialization.
Ordering, Slots and Keyword-Only Fields
The option order=True generates __lt__, __le__, __gt__ and __ge__, which compare two instances as tuples of their fields, in the order of declaration. That order therefore decides the sorting key, and compare=False removes a field from it.
from dataclasses import dataclass, field
@dataclass(order=True)
class Version:
major: int
minor: int
label: str = field(default="", compare=False)
print(sorted([Version(1, 10), Version(1, 2, "beta"), Version(0, 9)]))
# Output: [Version(major=0, minor=9, label=''), Version(major=1, minor=2, label='beta'), Version(major=1, minor=10, label='')]
print(Version(1, 2, "rc") == Version(1, 2, "final")) # Output: True
try:
Version(1, 2) < (1, 3)
except TypeError as error:
print(error) # Output: '<' not supported between instances of 'Version' and 'tuple'
Numeric fields sort 1.10 after 1.2, which a comparison of version strings would not do, and the label is ignored both in sorting and in equality. Comparisons work only between instances of the same class.
Python 3.10 added two further options. slots=True generates __slots__ from the fields, with the memory savings and restrictions examined in the article devoted to __slots__, and kw_only=True makes every field a keyword-only parameter of the constructor, which removes the ordering constraint between fields with and without defaults. The same version added match_args, which is enabled by default and generates the __match_args__ used by the class patterns described in the article devoted to pattern matching.
Validation with __post_init__
The generated constructor only assigns values; it validates nothing. When the class defines __post_init__, the constructor calls it after the assignments, which is the place for checks and for fields computed from other fields.
from dataclasses import dataclass, field
@dataclass(slots=True, kw_only=True)
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
if self.width <= 0 or self.height <= 0:
raise ValueError("sides must be positive")
self.area = self.width * self.height
print(Rectangle(width=3, height=4)) # Output: Rectangle(width=3, height=4, area=12)
for attempt in (lambda: Rectangle(3, 4), lambda: Rectangle(width=-1, height=2)):
try:
attempt()
except (TypeError, ValueError) as error:
print(error)
# Output (CPython 3.12): Rectangle.__init__() takes 1 positional argument but 3 were given
# Output: sides must be positive
print(hasattr(Rectangle(width=1, height=1), "__dict__")) # Output: False
The field area is excluded from the constructor and computed in __post_init__, the keyword-only constructor rejects positional arguments, and the slotted instance has no __dict__. Because replace also goes through the constructor, a copy is validated in the same way as the original.
Pitfalls of Dataclasses
The generated code is correct for the common case, but its rules produce surprises at the edges. Five pitfalls are distinguished, which are the following:
- Unhashable by default. A mutable dataclass with
eq=Truesets__hash__toNone; it cannot be a dictionary key unless it is frozen. - Shallow freezing.
frozen=Trueprevents reassignment of fields, not the mutation of the objects they contain. - Declaration order as sorting key. With
order=True, the first field dominates every comparison, so the order of the fields must be chosen for sorting, orcompare=Falsemust exclude the irrelevant ones. - No type checking. Annotations identify fields; wrong types pass silently unless
__post_init__or a static checker verifies them. - Defaults after non-defaults. A field without a default cannot follow a field with one, also across inheritance;
kw_only=Trueor the markerKW_ONLYremoves the restriction.
Choosing the Right Tool
Consequently, a dataclass suits classes defined mainly by their data, and the following table compares it with the neighbouring tools of the standard library.
| Need | Recommended tool |
|---|---|
| Mutable record with generated methods | @dataclass |
| Immutable, hashable value object | @dataclass(frozen=True), with immutable field types |
| Many instances with low memory use | @dataclass(slots=True) |
| Constructors with many optional parameters | @dataclass(kw_only=True) |
| Lightweight immutable record that must behave as a tuple | typing.NamedTuple |
| Type description of a dictionary, for example decoded JSON | typing.TypedDict |
| Validation and conversion of external input | __post_init__, or a validation library |
Conclusion
It is concluded that @dataclass derives the constructor, the representation and the comparisons of a class from a declaration of annotated fields, and that its options add immutability, ordering, slots and keyword-only construction without any handwritten method. This magic has precise limits: annotations are not checked, freezing is shallow, and the declaration order decides how instances are sorted. Dataclasses describe what an object contains; abstract base classes, which describe what an object must be able to do, are developed in a future article of this series.