Programming languages · Intermediate · 22 min
Model records in Python with dataclasses
By Padding · Updated 18 Nov 2026
Python 3.15.2 · pytest 9.2 · python:3.15-slim (Debian)
You will replace a hand-written Python class with a dataclass, use the options that matter in practice (default_factory, frozen, slots, kw_only, order, __post_init__ and hidden fields), and finish with a tested Invoice and LineItem model that exports to JSON.
On this page
Most of the classes in a backend or data project are records: a customer, an order line, an API payload, a configuration block. They hold a few named values and need the same three methods every time: an __init__ that stores the values, a __repr__ you can read in a log, and an __eq__ that compares two records by their contents. Writing those by hand is slow, and the methods drift out of step when someone adds a field to __init__ and forgets __eq__.
The dataclasses module in the standard library writes those methods for you from the class's type annotations. You list the fields once, and the @dataclass decorator generates the rest. Options on the decorator and on each field then let you make records immutable, block attribute typos, force keyword arguments, sort records and check their values on creation.
You will build up those options one at a time with small scripts, then put them together in an invoice model with line items, JSON export and pytest tests. Money is kept as a whole number of the currency's smallest unit (kobo, cents, pesewas), which keeps totals exact.
Step 1 · Create a project with pytest
Make a throwaway project folder and add pytest as a development dependency. dataclasses is part of the standard library, so pytest is the only thing to install. The range allows patch releases of pytest 9.2 and nothing newer:
mkdir -p ~/dataclasses-demo
cd ~/dataclasses-demo
uv init --no-package
uv add --dev "pytest>=9.2,<9.3"uv creates pyproject.toml, a .venv folder with Python 3.15 and pytest in it, and a starter main.py you will not need.
Check it worked
uv run python --version
uv run pytest --versionThe first line says Python 3.15.2 (or a later 3.15 release) and the second says pytest 9.2.0 or a later 9.2 release.
Step 2 · Replace a hand-written class with a dataclass
Start with the class you would write without dataclasses. It stores three values, prints itself readably and compares by contents:
cat > customer_plain.py <<'PY'
class Customer:
def __init__(self, name, email, country="NG"):
self.name = name
self.email = email
self.country = country
def __repr__(self):
return (
f"Customer(name={self.name!r}, email={self.email!r}, "
f"country={self.country!r})"
)
def __eq__(self, other):
if other.__class__ is not self.__class__:
return NotImplemented
return (self.name, self.email, self.country) == (
other.name,
other.email,
other.country,
)
PYThat is 20 lines, and each field name appears four times. Now write the same record as a dataclass. Each annotated class attribute becomes a field, in the order you write them, and a value after = is that field's default:
cat > customer.py <<'PY'
import inspect
from dataclasses import dataclass, fields
import customer_plain
@dataclass
class Customer:
name: str
email: str
country: str = "NG"
new = Customer("Amara Obi", "amara@example.com")
old = customer_plain.Customer("Amara Obi", "amara@example.com")
print(new)
print("same repr as the hand-written class:", repr(new) == repr(old))
print("equal by contents:", new == Customer("Amara Obi", "amara@example.com"))
print("generated __init__:", inspect.signature(Customer))
print("fields:", [f.name for f in fields(Customer)])
print("hashable:", Customer.__hash__ is not None)
PY
uv run customer.pyThe decorator read the three annotations and generated __init__, __repr__ and __eq__ that match the hand-written ones. fields() lists what it found, which is how other tools (and you, later, in asdict) walk a dataclass. The type hints are not checked when the code runs: Customer(42, None) still works. A type checker such as mypy reads them before the code runs.
The last line is a detail worth knowing early. A class that defines __eq__ but can change after creation should not be used as a dictionary key or set member, so the decorator sets __hash__ to None. You will change that in the step on frozen records.
Check it worked
The first line of output is Customer(name='Amara Obi', email='amara@example.com', country='NG'). Then you see same repr as the hand-written class: True, equal by contents: True, a signature something like (name: str, email: str, country: str = 'NG') -> None, fields: ['name', 'email', 'country'] and hashable: False.
Step 3 · Give list fields their own default with default_factory
A list as a default value is a classic Python bug. A default is created once, when the function or class is defined, so every object that uses it shares the same list. The dataclass decorator refuses to let you write that bug. Run all three versions side by side:
cat > basket.py <<'PY'
from dataclasses import dataclass, field
class PlainBasket:
def __init__(self, items=[]):
self.items = items
first = PlainBasket()
second = PlainBasket()
first.items.append("rice")
print("plain class, second basket:", second.items)
try:
@dataclass
class BadBasket:
items: list[str] = []
except ValueError as err:
print("dataclass refused:", err)
@dataclass
class Basket:
items: list[str] = field(default_factory=list)
first = Basket()
second = Basket()
first.items.append("rice")
print("default_factory, second basket:", second.items)
PY
uv run basket.pyfield(default_factory=list) tells the generated __init__ to call list() for each new object. Any function with no arguments works as a factory: dict, set, datetime.now, or a lambda that builds something more specific. The decorator only rejects list, dict and set defaults (strictly, any unhashable default), so a mutable object of your own class as a default still gets shared. Use a factory for those too.
Check it worked
The plain class prints plain class, second basket: ['rice']: rice added to the first basket shows up in the second. The dataclass line starts dataclass refused: mutable default <class 'list'> for field items is not allowed, and the last line is default_factory, second basket: [].
Step 4 · Make value objects with frozen=True
Some records describe a value rather than a thing that changes: an amount of money, a coordinate, a date range. frozen=True makes every field read-only after creation. Because a frozen record cannot change, the decorator also generates a __hash__, so it works as a dictionary key or in a set. To get a changed copy, use dataclasses.replace:
cat > money.py <<'PY'
from dataclasses import FrozenInstanceError, dataclass, replace
@dataclass(frozen=True)
class Money:
amount_minor: int
currency: str
def __str__(self):
return f"{self.amount_minor / 100:,.2f} {self.currency}"
price = Money(150_000, "NGN")
try:
price.amount_minor = 1
except FrozenInstanceError as err:
print("cannot change it:", err)
discounted = replace(price, amount_minor=135_000)
print("original:", price)
print("copy:", discounted)
seen = {Money(150_000, "NGN"), Money(150_000, "NGN"), Money(2_500, "GHS")}
print("distinct prices:", len(seen))
PY
uv run money.pyreplace builds a new object by calling the class with the old values and your changes, so the original stays as it was. Frozen is shallow: it stops you rebinding a field, but if a field holds a list, the list itself can still be changed. Use a tuple for a sequence inside a frozen record.
amount_minor is the amount in the currency's smallest unit, so ₦1,500.00 is 150_000 kobo. Whole numbers add up exactly, where floats such as 0.1 + 0.2 do not. The division by 100 happens only when the value is printed.
Check it worked
The output is cannot change it: cannot assign to field 'amount_minor', original: 1,500.00 NGN, copy: 1,350.00 NGN and distinct prices: 2. The two identical NGN prices counted as one.
Step 5 · Catch typos with slots=True and force names with kw_only=True
A normal Python object keeps its attributes in a dictionary, so assigning to a misspelt name creates a new attribute and no error. slots=True gives the class a fixed set of attribute slots instead. The object uses less memory, and a typo raises AttributeError.
kw_only=True makes every field keyword-only. For a record with several fields of the same type, such as three strings, it stops someone passing them in the wrong order:
cat > address.py <<'PY'
from dataclasses import dataclass
@dataclass
class LooseAddress:
street: str
city: str
country_code: str
@dataclass(slots=True, kw_only=True)
class Address:
street: str
city: str
country_code: str
loose = LooseAddress("12 Marina Road", "Lagos", "NG")
loose.citty = "Abuja"
print("without slots the typo is silent, city is still:", loose.city)
home = Address(street="12 Marina Road", city="Lagos", country_code="NG")
try:
home.citty = "Abuja"
except AttributeError:
print("with slots the typo raises AttributeError")
print("has an attribute dictionary:", hasattr(home, "__dict__"))
try:
Address("12 Marina Road", "Lagos", "NG")
except TypeError:
print("positional arguments raise TypeError")
PY
uv run address.pyTwo trade-offs to know. A slotted class cannot get new attributes at run time, which a few libraries rely on. And kw_only makes calls longer, so use it on records with many fields, or where order mistakes are likely, rather than everywhere. To make only some fields keyword-only, give those field(kw_only=True).
Check it worked
You see four lines: the silent typo leaves city is still: Lagos, then with slots the typo raises AttributeError, has an attribute dictionary: False and positional arguments raise TypeError.
Step 6 · Sort records with order=True
order=True generates <, <=, > and >=. They compare two records as if they were tuples of their fields, in the order the fields are written. Put the fields you sort by first, and leave out the rest with field(compare=False):
cat > deliveries.py <<'PY'
from dataclasses import dataclass, field
@dataclass(order=True, frozen=True)
class Delivery:
priority: int
due: str
address: str = field(compare=False)
queue = [
Delivery(2, "2026-12-03", "Plot 7, Wuse II, Abuja"),
Delivery(1, "2026-12-05", "14 Oxford Street, Accra"),
Delivery(1, "2026-12-01", "3 Kenyatta Avenue, Nairobi"),
]
for item in sorted(queue):
print(item.priority, item.due, item.address)
same = Delivery(1, "2026-12-01", "another address") == queue[2]
print("address ignored when comparing:", same)
PY
uv run deliveries.pyDates in ISO format (YYYY-MM-DD) sort correctly as text, which is why due can be a string here; a datetime.date works just as well. compare=False takes the field out of == as well as <, which the last line shows. If that is not what you want, leave order off and sort with a key when you need it: sorted(queue, key=lambda d: d.due). A key is usually the better choice when a type has no single natural order.
Check it worked
The deliveries print in priority order, and by due date within the same priority: Nairobi, then Accra, then Abuja. The last line is address ignored when comparing: True.
Step 7 · Validate in __post_init__ and hide secrets from repr
The generated __init__ stores whatever it is given. To check the values, define __post_init__: the generated __init__ calls it after it has set every field. Raise an error there and the object is never handed back to the caller.
Records often hold something that must not end up in logs, such as an API key. field(repr=False) leaves a field out of the printed form. The key itself comes from an environment variable, never from the source code:
cat > account.py <<'PY'
import os
from dataclasses import asdict, dataclass, field
@dataclass
class PayoutAccount:
holder: str
bank_code: str
api_key: str = field(repr=False)
def __post_init__(self):
self.holder = self.holder.strip()
if not self.holder:
raise ValueError("holder must not be empty")
if not (self.bank_code.isdigit() and len(self.bank_code) == 3):
raise ValueError(f"bank_code must be 3 digits, got {self.bank_code!r}")
key = os.environ.get("PAYOUT_API_KEY", "not-set")
account = PayoutAccount(" Kofi Mensah ", "044", api_key=key)
print(account)
try:
PayoutAccount("Kofi Mensah", "44A", api_key=key)
except ValueError as err:
print("rejected:", err)
print("asdict still includes the key:", "api_key" in asdict(account))
PY
uv run account.pyIn your own app, set PAYOUT_API_KEY in the environment the app runs in (a secrets manager, or a .env file that is never committed). The script falls back to not-set so it runs without one.
__post_init__ can also tidy values, as the strip() on holder shows. Keep it to checks and small clean-ups: if building the object needs network calls or file reads, do that in a separate function that then calls the class.
The last line is the catch. repr=False only affects printing. asdict(), which you use next for JSON, still includes the field, so drop secrets yourself before you serialise a record.
Check it worked
The account prints as PayoutAccount(holder='Kofi Mensah', bank_code='044'), with the spaces removed and no api_key in sight. Then you see rejected: bank_code must be 3 digits, got '44A' and asdict still includes the key: True.
Step 8 · Build and test an Invoice and LineItem model
Now put the pieces together. A LineItem is a value: frozen, slotted and validated. An Invoice changes as you add items, so it is not frozen, but it is slotted, keyword-only and gets a fresh list per invoice. asdict() turns the whole thing, nested items included, into dictionaries and lists that json.dumps can write:
cat > invoices.py <<'PY'
import json
from dataclasses import asdict, dataclass, field
from datetime import date
@dataclass(frozen=True, slots=True)
class LineItem:
description: str
quantity: int
unit_price_minor: int
def __post_init__(self):
if not self.description.strip():
raise ValueError("description must not be empty")
if self.quantity < 1:
raise ValueError("quantity must be at least 1")
if self.unit_price_minor < 0:
raise ValueError("unit price must not be negative")
@property
def total_minor(self) -> int:
return self.quantity * self.unit_price_minor
@dataclass(slots=True, kw_only=True)
class Invoice:
number: str
customer: str
currency: str
issued: date
items: list[LineItem] = field(default_factory=list)
def __post_init__(self):
if len(self.currency) != 3 or not self.currency.isupper():
raise ValueError(f"currency must be a 3-letter code, got {self.currency!r}")
def add(self, item: LineItem) -> None:
self.items.append(item)
@property
def total_minor(self) -> int:
return sum(item.total_minor for item in self.items)
def to_dict(self) -> dict:
data = asdict(self)
data["issued"] = self.issued.isoformat()
data["total_minor"] = self.total_minor
return data
def to_json(self) -> str:
return json.dumps(self.to_dict(), ensure_ascii=False, indent=2)
PY
cat > invoice_demo.py <<'PY'
from datetime import date
from invoices import Invoice, LineItem
invoice = Invoice(number="INV-0042", customer="Adaeze Stores", currency="NGN", issued=date(2026, 11, 18))
invoice.add(LineItem("Ọ̀gẹ̀dẹ̀ (plantain) chips, 500 g", 3, 120_000))
invoice.add(LineItem("Delivery within Lagos", 1, 250_000))
print(invoice.to_json())
PY
uv run invoice_demo.pyThe two @property totals are worked out from the items each time, so they cannot fall out of step with the list. asdict does not call properties, so to_dict adds the invoice total itself, and turns the date into an ISO string because JSON has no date type.
ensure_ascii=False keeps the Yoruba tone marks in the description as readable text. Without it, json.dumps writes each code point (letter or tone mark) as an escape, so ẹ becomes \u1eb9 and the combining grave accent becomes \u0300. Both forms are valid JSON, but the readable one is what you want in files people open, in names, addresses and product lists in Yoruba, Amharic, Arabic or any language outside plain English. When you write this JSON to a file, open it with encoding="utf-8".
Now write tests that pin down the behaviour you have built:
cat > test_invoices.py <<'PY'
import json
from dataclasses import FrozenInstanceError, replace
from datetime import date
import pytest
from invoices import Invoice, LineItem
def make_invoice(**changes):
values = dict(number="INV-1", customer="Test Ltd", currency="KES", issued=date(2026, 11, 1))
values.update(changes)
return Invoice(**values)
def test_line_item_total():
assert LineItem("Airtime bundle", 4, 5_000).total_minor == 20_000
def test_invoice_total_adds_every_item():
invoice = make_invoice()
invoice.add(LineItem("Tea, 1 kg", 2, 65_000))
invoice.add(LineItem("Delivery", 1, 20_000))
assert invoice.total_minor == 150_000
def test_each_invoice_gets_its_own_item_list():
first, second = make_invoice(), make_invoice(number="INV-2")
first.add(LineItem("Tea, 1 kg", 1, 65_000))
assert second.items == []
@pytest.mark.parametrize("quantity, price", [(0, 100), (-1, 100), (1, -5)])
def test_bad_line_items_are_rejected(quantity, price):
with pytest.raises(ValueError):
LineItem("Tea, 1 kg", quantity, price)
def test_replace_runs_validation_again():
item = LineItem("Tea, 1 kg", 1, 65_000)
assert replace(item, quantity=3).total_minor == 195_000
with pytest.raises(ValueError):
replace(item, quantity=0)
def test_line_items_cannot_be_changed():
item = LineItem("Tea, 1 kg", 1, 65_000)
with pytest.raises(FrozenInstanceError):
item.quantity = 10
def test_currency_must_be_a_code():
with pytest.raises(ValueError, match="3-letter"):
make_invoice(currency="shillings")
def test_json_export_round_trips():
invoice = make_invoice()
invoice.add(LineItem("Café au lait", 2, 30_000))
data = json.loads(invoice.to_json())
assert data["issued"] == "2026-11-01"
assert data["total_minor"] == 60_000
assert data["items"] == [
{"description": "Café au lait", "quantity": 2, "unit_price_minor": 30_000}
]
assert "Café" in invoice.to_json()
PY
uv run pytest -qThe test for separate item lists guards the bug from the default_factory step. The replace test shows something useful: replace calls __init__, so __post_init__ runs again and an invalid copy is rejected just like an invalid original.
Check it worked
The demo prints the invoice as indented JSON, with the plantain chips description shown with its tone marks, "issued": "2026-11-18" and "total_minor": 610000 at the end (₦6,100.00). pytest ends with a line like 10 passed in 0.05s: eight test functions, one of them run three times by parametrize.
Step 9 · Clean up
Remove the demo project. Python, uv and anything outside the folder stay as they were:
cd ~
rm -rf ~/dataclasses-demoCheck it worked
ls ~/dataclasses-demo now reports that there is no such file or directory.
Next steps
Dataclasses are the right default for records inside your own code. Three neighbours are worth knowing by name:
typing.NamedTuple(standard library) when the record must also behave as a tuple, for example to unpack it or to pass it to code that expects one.- attrs, the third-party library dataclasses grew out of, when you want built-in validators and converters on each field and are happy to add a dependency.
- Pydantic when data arrives from outside (JSON from an API, form input, configuration files) and must be parsed and converted, with clear error messages, before you trust it.
From here:
- Let a type checker read the annotations you wrote: add type hints to Python code and check them with mypy.
- Save the invoice JSON to disk and read it back: read and write files and JSON in Python.
- Go further with fixtures and parametrize: write and run tests in Python with pytest.
- Revisit the basics of classes, methods and
__repr__: write your first class in Python.
Related tutorials
- Write safer PHP with strict types, enums and readonly classesYou will take a loosely typed PHP 8.5 order script that gets totals quietly wrong and turn it into a typed domain model with strict types, a backed enum, readonly value objects and match, then prove it with a clean PHPStan 2.3 run.
- Write reusable TypeScript with genericsYou will replace three copy-pasted lookup functions with one generic function, then build a type-safe pluck, a Result type, a hand-written mapped type and a tested fetchJson helper in TypeScript 7.
- Write regular expressions you can read and testYou will build a small, tested Python module that pulls dates, money amounts and Nigerian and Kenyan phone numbers out of messy SMS text, and know how to port its patterns to JavaScript and when to stop using a regex.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials