Dataclasses: Classes That Hold Data
The @dataclass decorator writes a data-holding class's __init__, __repr__ and == for you from a list of fields with types, with defaults for the fields a call can leave out and default_factory for a fresh list in every object.
Journeyman · Python · OOP · Updated
After this lesson you can
- Write a dataclass with typed fields and defaults, using field(default_factory=list) for a list
- Use the __init__, __repr__ and == a dataclass writes, and choose a dataclass for a class that mainly holds data
Key takeaways
- A class that mostly holds data repeats self.plant = plant for every field, prints as a memory address, and two objects with the same data aren't equal.
- The decorator @dataclass (read "at dataclass") writes init, repr and == from the fields, each a name and a type hint such as plant with the type str.
- A field with a default can be left out when an object is made, and fields with defaults come after the ones without.
- A list field needs field(default_factory=list), so each object gets a new empty list of its own.
- A dataclass is still a class with methods. Choose it when a class mainly holds data, and a plain class when making an object takes more work.
Many classes you'll write exist mainly to hold data: an order's items, a contact's name and phone number, one row of a report. Python has a shortcut that writes the routine parts of those classes for you, and you'll see it all over real projects, in settings, records and the data a web API sends back.
The example is Leaf & Sprout, a houseplant app, and its care log: a record of the days each plant was watered.
The same lines in every data class
Here's the care log as a plain class:
from datetime import date
class CareLog:
def __init__(self, plant, waterings, notes):
self.plant = plant
self.waterings = waterings
self.notes = notes
first = CareLog("Fern", [date(2026, 5, 2)], "likes the bathroom")
second = CareLog("Fern", [date(2026, 5, 2)], "likes the bathroom")
print(first == second)
False
Three fields, and each name is written three times. Add a field and you change the def line and add another line under it. Worse, two logs holding exactly the same data aren't equal: for a plain object, == asks "is this the very same object?", and these are two objects. And print(first) shows a memory address, as any class without __str__ or __repr__ does.
@dataclass writes them for you
A paper form lists its blanks (Plant, Waterings, Notes), and everybody fills in the same ones. A dataclass is a class written as that list of blanks, called fields, and Python writes the methods around them:
from dataclasses import dataclass
from datetime import date
@dataclass
class CareLog:
plant: str
waterings: list[date]
notes: str
first = CareLog("Fern", [date(2026, 5, 2)], "likes the bathroom")
second = CareLog("Fern", [date(2026, 5, 2)], "likes the bathroom")
print(first)
print(first == second)
CareLog(plant='Fern', waterings=[datetime.date(2026, 5, 2)], notes='likes the bathroom')
True
@dataclass(read "at dataclass") is a decorator: a line starting with@that adds features to the class or function right under it. This one comes from Python'sdataclassesmodule.plant: stris a field: a name, a colon and a type hint, read "plant is a str".list[date]is read "a list of dates". A hint says what a field should hold. Python doesn't check it while the program runs; Type Hints: Saying What a Value Should Be, in Module 4, shows the tools that do.- From the fields, the decorator writes
__init__(its parameters in the fields' order),__repr__(the printout above, whichprint()and lists use) and__eq__(read "dunder eq"), the method behind==, which compares the fields one by one.
Each field's name is written once instead of three times, and the class prints and compares the way you'd expect.
Defaults, and a fresh list for every log
Most logs start with no waterings and no notes. Give a field a default with =, as you would a function's parameter, and a call can leave it out. A list is the exception. Try [] as a default:
from dataclasses import dataclass
from datetime import date
@dataclass
class CareLog:
plant: str
waterings: list[date] = []
notes: str = ""
Python stops before the class is even finished, and the traceback's last line says why: ValueError: mutable default <class 'list'> for field waterings is not allowed: use default_factory. A default is made once, so one [] would be one list shared by every log, and watering the fern would show up in the cactus's log too. That's the mutable default trap: mutable means it can be changed in place, as a list can.
field(default_factory=list) says "call list() to make a new, empty list for each new object":
from dataclasses import dataclass, field
from datetime import date
@dataclass
class CareLog:
plant: str
waterings: list[date] = field(default_factory=list)
notes: str = ""
def record(self, day):
self.waterings.append(day)
fern_log = CareLog("Fern")
cactus_log = CareLog("Cactus", notes="sunny window")
fern_log.record(date(2026, 5, 2))
fern_log.record(date(2026, 5, 5))
print(fern_log)
print(cactus_log)
CareLog(plant='Fern', waterings=[datetime.date(2026, 5, 2), datetime.date(2026, 5, 5)], notes='')
CareLog(plant='Cactus', waterings=[], notes='sunny window')
Fields with defaults come after the fields without, as parameters with defaults do. And a dataclass is still a class: record is an ordinary method that uses self like any other.
When a dataclass fits
Reach for @dataclass when a class mainly holds data and its __init__ would only store each argument: a log, an order, a contact. Keep a plain class when making an object takes real work, such as working out a value from the arguments or checking them first. Either way, you can add any methods you like, and a dataclass can still have its own __str__ when you want a friendlier printout than __repr__.
Do it: write a reminder dataclass
Leaf & Sprout's reminders cover the other jobs a plant needs, such as feeding it or moving it to a bigger pot.
plant: the plant's name, such as"Fern".task: the job,"feed"unless the reminder says otherwise.every_days: how often the job comes around, in days,30unless the reminder says otherwise.done_on: the dates the job was done, empty when a reminder is made.
Your job: write Reminder as a dataclass with those four fields, in that order.
plantis astrwith no default.taskis astrthat defaults to"feed", andevery_daysanintthat defaults to30.done_onis alistthat starts empty, a new list for each reminder: adding a date to one reminder's list doesn't change another's.
Worked through: Reminder("Fern") is a reminder to feed the fern every 30 days, done on no dates yet. It prints as Reminder(plant='Fern', task='feed', every_days=30, done_on=[]), and it's equal (==) to Reminder("Fern", "feed", 30, []).
Practiced live on the lesson page: write the Python right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Most classes in real code hold data, and @dataclass lets you write only what makes each one different: its fields.