Python dataclasses, enums and datetimes: modelling a business domain
Model real business data in Python with dataclasses, frozen value objects, StrEnum for fixed choices, type hints checked by mypy, and timezone-aware datetimes.
Good code reads like the business talks. If operations says "a shipment has a recipient and one or
more parcels", the code should have a Shipment with a recipient and parcels. Python gives you
three tools that make this easy: dataclasses, enums and type hints.
Dataclasses
A dataclass is a class whose main job is to hold data. You list the fields with their types, and
Python writes __init__, __repr__ and __eq__ for you:
from dataclasses import dataclass, field
@dataclass
class Shipment:
id: str
customer_id: str
parcels: tuple[Parcel, ...]
status: Status = Status.CREATED
history: list[StatusChange] = field(default_factory=list)- Fields with defaults come after fields without.
- For a mutable default (a list, a dict) use
field(default_factory=list). Writing= []would share one list between every shipment, a classic Python bug. - Two dataclasses are equal when all their fields are equal, which makes tests pleasant:
assert shipment.recipient == Address("Krause", "Lindenweg 4", ...).
Frozen dataclasses for values
Some things are values: an address, a parcel's size, a price. They describe something; they don't change. If a customer moves, that's a different address.
@dataclass(frozen=True)
class Parcel:
weight_grams: int
length_cm: int
width_cm: int
height_cm: int
p = Parcel(2500, 30, 20, 10)
p.weight_grams = 0 # FrozenInstanceErrorFreezing catches accidental changes, including typos: on a normal class, p.weigth_grams = 0
silently creates a new attribute. Frozen dataclasses are also hashable, so they can be set members
and dict keys.
Other things are entities: they have an identity and change over time. A shipment NS-000041
moves from "created" to "delivered" but stays the same shipment. Entities are normal (mutable)
dataclasses, and you change them only through methods that enforce the rules, like
change_status.
Computed values: properties
A value that's derived from fields shouldn't be stored twice. Make it a property:
@dataclass(frozen=True)
class Address:
country: str
...
@property
def zone(self) -> int:
return ZONES[self.country]Enums for fixed choices
When a field can only be one of a few values (a status, a service level), use an enum instead of bare strings. Typos become errors, and your editor can autocomplete.
from enum import StrEnum
class ServiceLevel(StrEnum):
STANDARD = "standard"
EXPRESS = "express"
ServiceLevel("express") # ServiceLevel.EXPRESS
ServiceLevel("overnight") # ValueError: 'overnight' is not a valid ServiceLevel
ServiceLevel.EXPRESS == "express" # True: a StrEnum is also a strStrEnum (Python 3.11+) is handy for data that ends up in JSON or a database, because each member
is its string. Compare members with is: if shipment.service is ServiceLevel.EXPRESS:.
To turn user input into an enum, catch the ValueError:
try:
service = ServiceLevel(text.strip().lower())
except ValueError:
errors.append(FieldError("service", "must be standard or express"))Type hints and mypy
Type hints say what each variable, argument and return value holds:
def quote(shipment: Shipment) -> Quote: ...
def parse_weight_kg(text: str) -> int | None: ...Python doesn't enforce them at runtime. mypy does, before you run anything: python -m mypy .
reports a str passed where an int is expected, a missing None check, a misspelled attribute.
The Devventura Python projects run mypy in strict mode, which also requires every function to
be annotated.
A few hints you'll use constantly:
| Hint | Means |
|---|---|
int | None | an int, or None ("maybe a value") |
list[Parcel] | a list of parcels |
tuple[Parcel, ...] | a tuple of any length, all parcels |
dict[str, int] | a dict from str to int |
Mapping[str, object] | anything dict-like you only read from |
object | anything at all: check it before you use it |
Prefer object over Any for "I don't know yet": mypy makes you check object with
isinstance before using it, while Any switches checking off.
Datetimes with a timezone
A datetime is either naive (no timezone) or aware (has tzinfo). Only aware datetimes
are exact instants:
from datetime import UTC, datetime, timedelta, timezone
pickup = datetime(2026, 3, 2, 9, 0, tzinfo=UTC)
berlin = timezone(timedelta(hours=1))
scan = datetime(2026, 3, 2, 10, 30, tzinfo=berlin) # 09:30 UTC
scan > pickup # True: compared as instants
datetime(2026, 3, 2, 10, 30) > pickup # TypeError: naive vs awareRules of thumb:
- Store and compare times as aware datetimes, ideally in UTC:
datetime.now(UTC). - Check
at.tzinfo is not Noneat the boundary and refuse naive ones. - Convert to local time only for display.
- For real timezones with daylight saving, use
zoneinfo.ZoneInfo("Europe/Berlin"), not a fixed offset.
Questions and answers
- When should I use a frozen dataclass?
- For values that describe something and never change once created, like an address, a price or a parcel's size. Frozen dataclasses can't be modified by accident, can be compared by value and can be used as dict keys.
- What is a timezone-aware datetime?
- A datetime with tzinfo set, such as datetime(2026, 3, 2, 9, 0, tzinfo=UTC). It describes one exact instant. A naive datetime has no timezone, so '09:00' could mean different moments in different places.
Read next
- Validating input: check once at the boundary, then trust your types
Where to validate data, how to report every problem at once with field paths, and how to write error messages people can act on. With examples in Python.
- Testing with pytest: run, read and write Python tests
How to run pytest, read a failing test, select tests with markers and -k, share setup with fixtures, cover many cases with parametrize, and test exceptions.
- State machines in practice: transition tables, guards and event logs
Model order statuses, CSV quoting and regex matching as state machines: one transition table, guards for business rules, event logs you can replay, and NFAs that track several states.