Python dataclasses: Less Boilerplate for Data Classes
What you’ll learn
Section titled “What you’ll learn”- How
@dataclassgenerates__init__,__repr__, and__eq__from your fields. - How
field(default_factory=...)safely initializes mutable defaults. - How
frozen=Truemakes a dataclass immutable and hashable. - How
slots=True(Python 3.10+) reduces memory and blocks new attributes. - How
__post_init__computes derived fields after the generated__init__runs. - How inheritance works with dataclasses, and when a dataclass beats a namedtuple or a plain class.
Summary
Section titled “Summary”dataclasses, added in Python 3.7, generates the boilerplate methods a data-holding class needs. Decorate a class with @dataclass and list its fields, and the decorator writes __init__, __repr__, and __eq__ for you. It also handles the mutable-default trap with field(default_factory=...), supports immutability with frozen=True, memory savings with slots=True, and derived fields with __post_init__. A dataclass is the default choice for a record that has fields, defaults, and maybe a method or two.
The problem it solves
Section titled “The problem it solves”Writing a class to hold data by hand means writing the same __init__, __repr__, and __eq__ over and over, and getting any of them subtly wrong. The mutable-default trap appears because a literal [] as a default is shared across instances. Dataclasses remove the repetition and the trap in one move.
Hand-written class:
class Order: def __init__(self, order_id, customer, amount, tags=None): self.order_id = order_id self.customer = customer self.amount = amount self.tags = tags if tags is not None else []
def __repr__(self): return f"Order({self.order_id!r}, {self.customer!r}, {self.amount!r}, {self.tags!r})"
def __eq__(self, other): if not isinstance(other, Order): return NotImplemented return (self.order_id, self.customer, self.amount, self.tags) == ( other.order_id, other.customer, other.amount, other.tags )That is a lot of code for “a record with four fields and a list default.” The dataclass version is four lines.
How it works
Section titled “How it works”The basics
Section titled “The basics”Decorate a class with @dataclass and declare each field with a type annotation. The decorator generates __init__ (in field order), __repr__, and __eq__ (comparing as tuples of fields). A field with a default value keeps that default in the generated __init__.
from dataclasses import dataclass
@dataclassclass Order: order_id: int customer: str amount: float status: str = "pending"
o = Order(1023, "Acme", 42.5)print(o)# Order(order_id=1023, customer='Acme', amount=42.5, status='pending')print(o == Order(1023, "Acme", 42.5))# True <- equality compares fieldsprint(o.status)# pendingFields without defaults must come before fields with defaults, the same rule as function parameters. The generated __init__ accepts them in declaration order.
Mutable defaults with field(default_factory=...)
Section titled “Mutable defaults with field(default_factory=...)”A literal mutable default like tags: list = [] would be shared across every instance, which is the mutable-default bug. Dataclasses forbid this and require field(default_factory=...), which calls the factory for each new instance so the default is fresh.
from dataclasses import dataclass, field
@dataclassclass Order: order_id: int customer: str amount: float = 0.0 tags: list = field(default_factory=list)
a = Order(1023, "Acme")b = Order(1024, "Globex")a.tags.append("rush")print(a.tags, b.tags)# ['rush'] [] <- each instance gets its own listdefault_factory=list calls list() per instance, so a.tags and b.tags are distinct lists. This is the type-safe replacement for the hand-written if tags is None: tags = [] sentinel.
frozen=True for immutability
Section titled “frozen=True for immutability”A frozen dataclass cannot be modified after construction: attribute assignment raises FrozenInstanceError. Frozen instances are hashable, so they work as dictionary keys and set members, provided their fields are hashable.
from dataclasses import dataclass
@dataclass(frozen=True)class Customer: customer_id: int name: str
c = Customer(1, "Acme")print(hash(c))# a stable integer hashlookup = {c: "vip"}print(lookup[Customer(1, "Acme")])# vip <- frozen + hashable fields = usable as a key# c.name = "Globex" # FrozenInstanceErrorUse frozen=True for value objects that should not change, such as a customer or a money amount paired with a currency.
slots=True for less memory (Python 3.10+)
Section titled “slots=True for less memory (Python 3.10+)”slots=True gives the class a __slots__ declaration, which stores fields in a fixed layout instead of a per-instance __dict__. The class uses less memory and blocks adding new attributes, at the cost of some flexibility. It requires Python 3.10 or later.
import sysfrom dataclasses import dataclass
if sys.version_info >= (3, 10): @dataclass(slots=True) class Order: order_id: int customer: str amount: float
o = Order(1023, "Acme", 42.5) print(o) # Order(order_id=1023, customer='Acme', amount=42.5) print(hasattr(o, "__dict__")) # False <- no per-instance dict, fields live in slotselse: print("slots=True requires Python 3.10+")The version guard keeps the file runnable on Python 3.9, where the slots argument does not exist. On 3.10 and later it runs the slotted class and confirms the instance has no __dict__.
__post_init__ for derived fields
Section titled “__post_init__ for derived fields”A dataclass can define __post_init__, which the generated __init__ calls after setting the declared fields. Use it to compute derived fields, validate input, or initialize fields declared with field(init=False) so they are not constructor parameters.
from dataclasses import dataclass, field
@dataclassclass Order: order_id: int amount: float currency: str = "USD" # init=False: not a constructor param, computed in post_init formatted: str = field(init=False)
def __post_init__(self): self.formatted = f"{self.currency} {self.amount:.2f}"
o = Order(1023, 42.5)print(o.formatted)# USD 42.50field(init=False) removes formatted from the generated __init__, and __post_init__ sets it. The field still appears in __repr__ and __eq__ by default, which you can change with field(init=False, repr=False, compare=False) when you want it excluded.
Inheritance
Section titled “Inheritance”A subclass dataclass inherits the parent’s fields, with the subclass’s fields appended after. The usual parameter-ordering rule applies: a field with a default in the parent keeps its default, and a subclass field without a default after a defaulted parent field raises a TypeError, because the generated __init__ would have a non-default after a default.
from dataclasses import dataclass
@dataclassclass Base: order_id: int
@dataclassclass ShippedOrder(Base): order_id: int carrier: str = "FedEx" tracking: str = ""
o = ShippedOrder(1023, tracking="TRK-9")print(o)# ShippedOrder(order_id=1023, carrier='FedEx', tracking='TRK-9')The subclass redeclares order_id (so it can stay first) and adds carrier and tracking, both with defaults so they come after the parent’s non-default field without trouble.
Realistic example
Section titled “Realistic example”OrdersPortal models an order with a mutable tag list, a frozen customer value object, and a derived formatted amount. Each pattern maps to a dataclass feature.
from dataclasses import dataclass, field
@dataclass(frozen=True)class Customer: customer_id: int name: str
@dataclassclass Order: order_id: int customer: Customer amount: float status: str = "pending" tags: list = field(default_factory=list)
def add_tag(self, tag): self.tags.append(tag) return self
acme = Customer(1, "Acme")order = Order(1023, acme, 1500.0).add_tag("rush")print(order)# Order(order_id=1023, customer=Customer(customer_id=1, name='Acme'), amount=1500.0, status='pending', tags=['rush'])print(hash(acme))# a stable hash, so a frozen Customer is usable as a keyThe frozen Customer is a value object: equality by fields, usable as a key. The mutable Order has a fresh tag list per instance and a method, neither of which a plain namedtuple supports well.
Production patterns
Section titled “Production patterns”- Use
frozen=Truefor value objects. Immutable records are safer to share across threads and usable as dict keys. Default to frozen unless you need mutation. - Use
default_factoryfor every mutable default. It is the only correct way to give a dataclass a list, dict, or set default. - Add
slots=Truefor many small instances. When you allocate millions of records, the memory and attribute-access savings add up. Measure first; slots can interfere with some patterns that expect a__dict__. - Keep methods off data classes unless they are intrinsic. A dataclass with one or two small methods is fine; one with a large API is probably a domain class that should not be a dataclass.
Common mistakes
Section titled “Common mistakes”- Using a mutable literal default.
tags: list = []raisesValueErrorat class creation: dataclasses forbid it. Usefield(default_factory=list). - Putting a non-default field after a default field. The generated
__init__follows parameter ordering rules, so a field without a default after one with a default is aTypeError. Reorder so defaults come last. - Expecting a frozen dataclass to be hashable with unhashable fields. A frozen class is hashable only if its fields are hashable. A frozen dataclass containing a list is still not hashable.
- Forgetting that
__eq__compares fields as a tuple. Equality is field-by-field in order, so two instances with the same field values are equal. If you want identity equality, do not use a dataclass, or override__eq__. - Using
slots=Truewith a subclass that also needs a__dict__. Slots prevent adding attributes outside the declared set, which breaks some mixin and serialization patterns. Test before adopting slots broadly.
When to use it and when not to
Section titled “When to use it and when not to”| Need | Use |
|---|---|
| A record with fields, defaults, maybe a method | @dataclass |
| An immutable, hashable value object | @dataclass(frozen=True) |
| A tiny fixed record, no defaults or methods | namedtuple |
| A class with significant behavior and state | a regular class |
A namedtuple is lighter and still a real tuple, but it offers no mutable fields, no defaults without extra syntax, and no methods without a subclass. A dataclass is the better default when you need any of those.
Compatibility
Section titled “Compatibility”dataclasses arrived in Python 3.7. frozen, __post_init__, and field(init=False) have been available since then. slots=True was added in Python 3.10. The examples here run on Python 3.9 and later, with the slots=True example guarded so it runs only on 3.10+.
Interview questions
Section titled “Interview questions”1. Why does dataclasses forbid tags: list = []?
A literal mutable default is evaluated once and shared across all instances, which is the mutable-default bug. The decorator refuses it and requires field(default_factory=list), which calls the factory per instance so each gets a fresh list.
2. What does frozen=True change?
It makes assignment to a field raise FrozenInstanceError after construction, and it makes the class hashable when its fields are hashable. That lets frozen dataclasses serve as dictionary keys and set members.
3. When would you choose a namedtuple over a dataclass?
For a small, fixed, immutable record with no defaults and no methods, where you want it to also be a real tuple for unpacking and hashing. Anything with defaults, mutation, or methods is clearer as a dataclass.
4. Senior scenario: you have millions of Order dataclass instances and memory is a problem. What do you change?
Add slots=True (Python 3.10+) to drop the per-instance __dict__, which can cut memory by a third or more for small classes, and keep only the fields you need. Pair it with __post_init__-free designs to avoid work per construction. If slots are not an option because of a needed __dict__, consider a more compact representation such as a typed array or a database, and measure the change rather than assuming the saving.
Key takeaways
Section titled “Key takeaways”@dataclassgenerates__init__,__repr__, and__eq__from typed fields.- Mutable defaults need
field(default_factory=...); literal mutables are forbidden. frozen=Truemakes a dataclass immutable and hashable;slots=True(3.10+) saves memory.__post_init__computes derived fields;field(init=False)keeps them out of the constructor.- A dataclass beats a namedtuple when you need mutation, defaults, or methods; a regular class wins when behavior dominates data.
Related pages
Section titled “Related pages”- namedtuple — the lightweight immutable alternative.
- slots — the
__slots__mechanism thatslots=Truebuilds on. - the collections module —
namedtupleand other containers. - copy vs deepcopy — copying dataclass instances and their mutable fields.
- type hints — the annotations dataclass fields require.
Official references
Section titled “Official references”- Python 3 —
dataclassesmodule — the decorator,field,frozen,slots, and__post_init__. - PEP 557 — Data Classes — the original proposal.
- Python 3 —
dataclasses.field—default_factory,init,repr,compare. - Python 3 —
__slots__— the mechanism behindslots=True.