Appearance
3.13.8 — Dataclasses, Enums & Value Objects
Open almost any Python codebase and you will find classes like this one: an __init__ that copies five arguments onto self, a __repr__ that lists the same five names again, and an __eq__ that compares the same five names a third time. Add a sixth field and you must remember to update three methods. Forget one, and two different orders compare as equal. And somewhere nearby, order status is stored as the strings "paid", "Paid" and "PAID", depending on who wrote the code. This page covers the standard tools that remove both problems. @dataclass writes the boring methods for you. Enum gives a fixed set of named values. NamedTuple and TypedDict fill two narrower roles. At the end you will know which one to choose for each job, and where Pydantic fits.
1. @dataclass: the class decorator that writes code
You met class decorators in 3.13.5. @dataclass, added in Python 3.7 and described in PEP 557, is the most useful one in the standard library. It reads the annotated fields in your class body and writes methods based on them.
python
from dataclasses import dataclass
@dataclass
class OrderLine:
sku: str # (1)
quantity: int
unit_price: int = 0 # (2)
line = OrderLine("mug", 2, 450)
print(line) # (3)
print(line == OrderLine("mug", 2, 450)) # (4)text
OrderLine(sku='mug', quantity=2, unit_price=450)
True(1)Each name with a type annotation becomes a field. The annotation is required, but nothing checks the type at run time. Dataclasses do not validate.(2)A value after the annotation is the field's default.(3)A readable__repr__was written for you.(4)So was__eq__. It compares the fields in order, as if comparing two tuples.
What it generated, and how
Let us look at what the decorator added to the class.
python
import inspect
print(inspect.signature(OrderLine.__init__)) # (1)
print(OrderLine.__match_args__) # (2)
print(OrderLine.__hash__) # (3)
print(OrderLine.__init__.__code__.co_filename) # (4)text
(self, sku: str, quantity: int, unit_price: int = 0) -> None
('sku', 'quantity', 'unit_price')
None
<string>(1)A real__init__with the fields as parameters, in the order you wrote them.(2)__match_args__lets the class be used in amatchstatement by position. 3.13.16 shows it.(3)__hash__isNone, so instances are unhashable. This is the rule from 3.13.6: defining__eq__without__hash__makes a class unhashable, because a mutable object must not be a dict key.(4)The__init__came from a file called<string>. This is the behind-the-scenes trick. The decorator builds the source code of each method as a text string, such asdef __init__(self, sku: str, quantity: int, unit_price: int = 0):followed byself.sku = skuand so on, and then runs that text with the built-inexec. The result is exactly as fast as a hand-written method, because it is a hand-written method, just written by a program.
How did the decorator know the fields? It read the class's __annotations__, which keep the order you wrote them in, because dicts are ordered (3.13.3). It stores what it learned in __dataclass_fields__, which the helper functions in section 3 read.
2. Fields: defaults, factories and per-field options
The mutable default problem, solved
You already know the mutable default trap from 3.13.4 and the shared class attribute trap from 3.13.6. A dataclass would hit both, because a default value is stored once and shared. So it refuses.
python
from dataclasses import dataclass
try:
@dataclass
class Order:
items: list = []
except ValueError as error:
print("ValueError:", error)text
ValueError: mutable default <class 'list'> for field items is not allowed: use default_factoryThe error message names the fix. field(default_factory=...) takes a function that is called fresh for every new instance.
python
from dataclasses import dataclass, field
from datetime import datetime, timezone
@dataclass
class OrderLine:
sku: str
quantity: int
unit_price: int = 0
@dataclass
class Order:
order_id: str
lines: list[OrderLine] = field(default_factory=list) # (1)
created_at: datetime = field(
default_factory=lambda: datetime.now(timezone.utc), repr=False) # (2)
notes: str = field(default="", compare=False) # (3)
def __post_init__(self): # (4)
if not self.order_id.startswith("ORD-"):
raise ValueError(f"bad order id {self.order_id!r}")
@property
def total(self): # (5)
return sum(line.quantity * line.unit_price for line in self.lines)
first = Order("ORD-1")
second = Order("ORD-2")
first.lines.append(OrderLine("mug", 2, 450))
print(first, second.lines, first.total)
try:
Order("1")
except ValueError as error:
print("ValueError:", error)text
Order(order_id='ORD-1', lines=[OrderLine(sku='mug', quantity=2, unit_price=450)], notes='') [] 900
ValueError: bad order id '1'(1)listis called for each new order, sosecond.linesis its own empty list.(2)The clock is read once per order, not once at import.repr=Falsekeeps the long timestamp out of the printed form.(3)compare=Falseleavesnotesout of__eq__, so two orders with the same data but different notes are equal.(4)__post_init__runs at the end of the generated__init__. It is the place for checks and for fields computed from other fields.(5)A dataclass is a normal class. You can add properties and methods freely.
Fields after a default, and kw_only
Python does not allow a parameter without a default to follow one with a default. The generated __init__ follows the same rule, which causes trouble with inheritance.
python
from dataclasses import dataclass
@dataclass
class Base:
id: int
note: str = ""
try:
@dataclass
class Customer(Base):
name: str # (1)
except TypeError as error:
print("TypeError:", error)text
TypeError: non-default argument 'name' follows default argument 'note'(1)Inherited fields come first, so the__init__would be(id, note="", name), which is invalid.
Python 3.10 added keyword-only fields to fix this. With kw_only=True on the whole class, every field must be passed by name, so order no longer matters. It also makes calls self-explaining, exactly like keyword-only parameters in 3.13.4.
python
from dataclasses import dataclass
@dataclass(kw_only=True)
class ShipRequest:
order_id: str
carrier: str = "dhl"
insured: bool = False
print(ShipRequest(order_id="ORD-1", insured=True))
try:
ShipRequest("ORD-1")
except TypeError as error:
print("TypeError:", error)text
ShipRequest(order_id='ORD-1', carrier='dhl', insured=True)
TypeError: ShipRequest.__init__() takes 1 positional argument but 2 were givenFor a single class you can also place the special marker _: KW_ONLY in the body, and every field after it becomes keyword-only.
3. Frozen, slotted and ordered: value objects
A value object is an object defined entirely by its values, with no identity of its own. Two ₹500 notes are interchangeable, and so are two Money(500) objects. Value objects should be immutable, so nobody can change a price that other code is relying on. Three options make a dataclass into a proper value object.
python
from dataclasses import dataclass, FrozenInstanceError, replace
@dataclass(frozen=True, slots=True, order=True) # (1)
class Money:
paise: int
currency: str = "INR"
price = Money(500)
try:
price.paise = 1 # (2)
except FrozenInstanceError as error:
print("FrozenInstanceError:", error)
print(replace(price, paise=900)) # (3)
print(hash(price) == hash(Money(500)), {Money(1), Money(1)}) # (4)
print(sorted([Money(9), Money(3)])) # (5)
print(hasattr(price, "__dict__"), Money.__slots__) # (6)text
FrozenInstanceError: cannot assign to field 'paise'
Money(paise=900, currency='INR')
True {Money(paise=1, currency='INR')}
[Money(paise=3, currency='INR'), Money(paise=9, currency='INR')]
False ('paise', 'currency')(1)Three switches at once:frozen,slotsandorder.(2)frozen=Truegenerates a__setattr__that refuses every assignment after creation.(3)To "change" a frozen object, make a new one.dataclasses.replacecopies an instance with some fields changed.(4)Because the object can no longer change, the decorator also generates__hash__from the fields. Frozen dataclasses can be dict keys and set members.(5)order=Truegenerates<,<=,>and>=, comparing fields in order like tuples.(6)slots=True, added in 3.10, generates__slots__from the fields. There is no instance__dict__, which saves memory as shown in 3.13.6.
One honest caveat about frozen. It blocks assignment to the fields, but a frozen dataclass holding a list still lets you append to that list. This is the same lesson as the tuple holding a list in 3.13.2. For truly immutable value objects, use immutable field types such as tuple and frozenset.
Helper functions
The dataclasses module has helpers that read the stored field information.
python
from dataclasses import asdict, fields
order = Order("ORD-7", [OrderLine("pen", 5, 40)])
print(asdict(order)["lines"]) # (1)
print([f.name for f in fields(Order)]) # (2)text
[{'sku': 'pen', 'quantity': 5, 'unit_price': 40}]
['order_id', 'lines', 'created_at', 'notes'](1)asdictconverts recursively, including nested dataclasses inside lists, which is handy before writing JSON.(2)fieldslists the field definitions, which is what generic code uses to work with any dataclass.
4. NamedTuple: a tuple with names
typing.NamedTuple creates a tuple subclass whose positions also have names. It is immutable, hashable and unpackable, because it is a tuple.
python
from typing import NamedTuple
class Location(NamedTuple):
lat: float
lng: float
store = Location(12.97, 77.59)
lat, lng = store # (1)
print(store, store.lat, store[0], lat) # (2)
print(store._asdict(), store._replace(lat=0.0)) # (3)text
Location(lat=12.97, lng=77.59) 12.97 12.97 12.97
{'lat': 12.97, 'lng': 77.59} Location(lat=0.0, lng=77.59)(1)It unpacks like any tuple.(2)Access by name or by position.(3)Helper methods start with an underscore so they cannot clash with your field names.
Use a NamedTuple when the value really is a small fixed record and code benefits from tuple behaviour: unpacking, or being returned from a function that used to return a plain tuple. Its tuple nature is also its weakness. Location(1, 2) == (1, 2) is True, and you cannot add a field without breaking every caller that unpacks it. For most domain objects, a frozen dataclass is the better default.
5. TypedDict: describing a dict's shape
Sometimes the data really is a dict, and must stay one: a JSON payload, or keyword arguments passed through several layers. TypedDict describes which keys the dict has and what types their values are, for the type checker only.
python
from typing import TypedDict, NotRequired
class OrderPayload(TypedDict):
order_id: str
quantity: int
coupon: NotRequired[str] # (1)
payload: OrderPayload = {"order_id": "ORD-1", "quantity": 2}
print(payload, type(payload)) # (2)text
{'order_id': 'ORD-1', 'quantity': 2} <class 'dict'>(1)NotRequiredmarks a key that may be missing.(2)At run time it is an ordinarydict. There is no class instance and no checking. A type checker such as mypy, however, will flagpayload["quantty"]as a typo andpayload["quantity"] = "two"as the wrong type.
This is the same idea as a TypeScript object type (3.7.2): a description of a shape, erased at run time. 3.13.12 covers static typing properly.
6. Enum: a fixed set of named values
Order status should be one of a small fixed set: pending, paid, shipped. Storing it as free-form strings invites "Paid" versus "paid" bugs, and nothing stops "payed". An enumeration, or enum, defines the allowed values once. Python added the enum module in 3.4 (PEP 435).
python
from enum import StrEnum, auto
class OrderStatus(StrEnum): # (1)
PENDING = auto() # (2)
PAID = auto()
SHIPPED = auto()
print(OrderStatus.PAID, repr(OrderStatus.PAID)) # (3)
print(OrderStatus("shipped"), OrderStatus.PAID == "paid") # (4)
print(OrderStatus.PAID.name, OrderStatus.PAID.value) # (5)
print(list(OrderStatus))
try:
OrderStatus("lost") # (6)
except ValueError as error:
print("ValueError:", error)text
paid <OrderStatus.PAID: 'paid'>
shipped True
PAID paid
[<OrderStatus.PENDING: 'pending'>, <OrderStatus.PAID: 'paid'>, <OrderStatus.SHIPPED: 'shipped'>]
ValueError: 'lost' is not a valid OrderStatus(1)StrEnum, added in Python 3.11, makes every member also a realstr.(2)auto()picks the value for you. ForStrEnum, it is the member name in lower case.(3)Printing gives the plain value.reprshows the full member.(4)Calling the enum with a value looks up the member. This is how you turn a string from a database or an HTTP request into a member. And because it is astr, it compares equal to its value.(5)Every member has anameand avalue.(6)An unknown value is rejected loudly, at the boundary, instead of travelling through the system.
How enums work inside
An enum is built by a metaclass, EnumType, the machinery from 3.13.7. When the class body finishes, the metaclass turns each assignment into a single instance of the class, stores them in order, and blocks you from creating more. That gives enums three properties.
- Each member is a singleton.
OrderStatus("paid") is OrderStatus.PAIDisTrue, soiscomparisons are safe and fast. - Members are fixed. You cannot add or reassign members after the class is created.
- Duplicate values become aliases. A second name with the same value does not create a new member. It points at the first one. Add the
@uniquedecorator to make duplicates an error instead.
The other enum types
Enumis the plain version. Members are not equal to their values, soStatus.PAID == "paid"isFalse. This strictness is a good default when the values never need to be compared with raw strings.IntEnummembers are alsoints. Use it when the values must work as numbers, such as priority levels that you sort.StrEnummembers are alsostrs. Use it when values travel through JSON, databases or HTTP.json.dumps({"status": OrderStatus.PAID})gives{"status": "paid"}with no extra code, and FastAPI shows the allowed values in its generated documentation.Flagmembers can be combined with|. That makes it a good fit for permission sets.
python
from enum import Flag, auto
class Permission(Flag):
READ = auto()
WRITE = auto()
REFUND = auto()
support_agent = Permission.READ | Permission.WRITE # (1)
print(support_agent)
print(Permission.REFUND in support_agent) # (2)text
Permission.READ|WRITE
False(1)auto()gives each flag its own bit: 1, 2, 4.|combines them.(2)inchecks whether a bit is set.
Enums can carry behaviour too. A method on the enum keeps rules about states next to the states themselves.
python
from enum import Enum
class Status(Enum):
PENDING = "pending"
PAID = "paid"
def can_ship(self):
return self is Status.PAID
print(Status.PAID.can_ship(), Status.PENDING.can_ship())text
True FalsePart 9's state pattern takes this idea further, with a class per state.
7. Choosing the right tool
| Need | Use |
|---|---|
| Domain object with behaviour | @dataclass |
| Immutable value, dict key | @dataclass(frozen=True) |
| Millions of small records | @dataclass(slots=True) |
| Small tuple-like result | NamedTuple |
| Shape of a JSON dict | TypedDict |
| Fixed set of choices | Enum / StrEnum |
| Untrusted input to validate | Pydantic BaseModel |
The last row is the important boundary. A dataclass trusts its caller. OrderLine("mug", "two", 450) is accepted without complaint, and the bug appears later, far from its cause. Data that comes from outside your program, such as an HTTP request, a file or a queue message, must be validated and often converted, turning the string "2" into the integer 2. That is Pydantic's job, and it is why FastAPI uses Pydantic models for request bodies. 3.14.2 covers it.
Cost matters too. On a typical laptop, creating a small dataclass takes about 140 nanoseconds, a NamedTuple about 290, a plain dict about 80, and a Pydantic model about 1,200, because Pydantic is validating every field. So the usual architecture is: validate with Pydantic at the edges, then pass plain dataclasses or Pydantic models through the inside of the program, without re-validating at every step.
What the interviewer will push on
"What does @dataclass generate?" __init__, __repr__ and __eq__ by default. Ordering methods with order=True. __hash__ and a blocking __setattr__ with frozen=True. __slots__ with slots=True. __match_args__ for pattern matching. The tell of real depth: it builds the methods' source text and runs it with exec, so they are as fast as hand-written ones.
"Why is a normal dataclass unhashable, and how do you make one hashable?" Defining __eq__ sets __hash__ to None, because a mutable object used as a dict key could change its hash and be lost. Use frozen=True, which generates a field-based hash. unsafe_hash=True exists, but you should be able to explain why it is unsafe.
"Dataclass, NamedTuple or Pydantic?" Dataclass for internal domain objects. NamedTuple when tuple behaviour such as unpacking is wanted. Pydantic for untrusted data that needs validation and conversion. The common wrong answer is "dataclasses validate types". They do not check anything at run time.
"How do you avoid a mutable default in a dataclass?" field(default_factory=list). Bonus: explain that the dataclass refuses a bare [] precisely to stop the shared-default bug.
"Why use an enum instead of string constants?" One place defines the allowed values. Invalid values are rejected when converting at the boundary. Members are singletons, so is works. And editors autocomplete them. Mention StrEnum for values that travel through JSON or databases.
Something to volunteer that nobody asks for: frozen=True stops you reassigning fields, but a list field can still be appended to. True value objects use immutable field types such as tuple and frozenset. It shows you understand what "immutable" actually guarantees.
Recall
@dataclassreads annotated fields and writes__init__,__repr__,__eq__and__match_args__, generating source text and running it withexec. It does not validate types.- Mutable defaults are refused. Use
field(default_factory=list).fieldalso takesrepr=Falseandcompare=False.__post_init__runs after__init__for checks. kw_only=Trueor_: KW_ONLYmakes fields keyword-only, which fixes default-ordering errors in subclasses.frozen=Truemakes a value object: no assignment, and a generated__hash__.slots=Trueremoves__dict__.order=Trueadds comparisons.replacecopies with changes,asdictconverts recursively.NamedTupleis a real tuple with names.TypedDictdescribes a dict's keys for type checkers only.- An enumeration (
Enum,IntEnum,StrEnum,Flag) is built by theEnumTypemetaclass. Members are singletons, duplicates become aliases, andStatus("paid")converts at the boundary. - Validate untrusted input with Pydantic at the edges. Use dataclasses inside.
Self-test: What file does a dataclass's __init__ come from, and why? Why does @dataclass reject items: list = []? What three switches turn a dataclass into a value object? When does Status.PAID == "paid" return True?
Quiz Bank
FoundationalDoes a dataclass check that quantity: int is really an int?
No. The annotation tells the decorator that quantity is a field and gives tools such as mypy and editors the expected type, but the generated __init__ simply assigns whatever it receives. OrderLine("mug", "two", 450) succeeds. You can add checks yourself in __post_init__, use descriptors, or use Pydantic, which validates and converts values against the annotations when the object is created.
AppliedA cache uses Order dataclass instances as dict keys and raises TypeError: unhashable type. What are your options?
A regular dataclass defines __eq__, so its __hash__ is None. The best option, if orders should not change after creation, is @dataclass(frozen=True), which generates a hash from the fields and blocks assignment, so the key can never change under the dict. If the object must stay mutable, key the cache by an immutable identifier instead, such as order.order_id. Avoid unsafe_hash=True on a mutable object. If a field changes after insertion, the hash changes and the entry becomes unreachable, which is a silent cache bug.
InterviewCompare dataclass, NamedTuple, TypedDict and Pydantic BaseModel in one minute.
A dataclass is a normal class with generated methods. It is mutable by default, can be frozen or slotted, and is the default for internal domain objects. It never validates. A NamedTuple is a tuple subclass with names: immutable, hashable and unpackable, good for small records and multi-value returns, but it compares equal to plain tuples and is hard to extend. A TypedDict is only a type-checker description of a dict's keys. At run time it is a plain dict. Use it for JSON-shaped data that must stay a dict. A Pydantic model validates and converts input against its annotations, serialises to JSON and produces a JSON Schema, at a higher cost per object. Use it at trust boundaries such as API requests and configuration.
StaffYour team stores order status as plain strings in the database and code. How would you introduce an enum without a risky big-bang change?
Define class OrderStatus(StrEnum) with the current canonical values. Because members are real strings, they compare equal to the existing values and serialise unchanged, so the database and JSON APIs do not change at all. Convert at the boundaries first: when reading from the database or an HTTP request, call OrderStatus(raw), which rejects unknown values. Log and fix the bad historical values that turn up, such as "Paid", with a data migration. Then change internal function signatures to accept OrderStatus and let the type checker find remaining raw strings. Finally add a database check constraint listing the allowed values, so the database enforces the same set the code does.
Next: you have used for loops on lists, dicts and your own OrderLines class. 3.13.9 shows the protocol behind every for loop, the generator functions that make it almost free to implement, and the with statement that guarantees cleanup.