Skip to content

Volume ITechnology

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 a match statement by position. 3.13.16 shows it.
  • (3) __hash__ is None, 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 as def __init__(self, sku: str, quantity: int, unit_price: int = 0): followed by self.sku = sku and so on, and then runs that text with the built-in exec. 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_factory

The 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) list is called for each new order, so second.lines is its own empty list.
  • (2) The clock is read once per order, not once at import. repr=False keeps the long timestamp out of the printed form.
  • (3) compare=False leaves notes out 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 given

For 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, slots and order.
  • (2) frozen=True generates a __setattr__ that refuses every assignment after creation.
  • (3) To "change" a frozen object, make a new one. dataclasses.replace copies 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=True generates <, <=, > 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) asdict converts recursively, including nested dataclasses inside lists, which is handy before writing JSON.
  • (2) fields lists 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) NotRequired marks a key that may be missing.
  • (2) At run time it is an ordinary dict. There is no class instance and no checking. A type checker such as mypy, however, will flag payload["quantty"] as a typo and payload["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 real str.
  • (2) auto() picks the value for you. For StrEnum, it is the member name in lower case.
  • (3) Printing gives the plain value. repr shows 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 a str, it compares equal to its value.
  • (5) Every member has a name and a value.
  • (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.

  1. Each member is a singleton. OrderStatus("paid") is OrderStatus.PAID is True, so is comparisons are safe and fast.
  2. Members are fixed. You cannot add or reassign members after the class is created.
  3. 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 @unique decorator to make duplicates an error instead.

The other enum types ​

  • Enum is the plain version. Members are not equal to their values, so Status.PAID == "paid" is False. This strictness is a good default when the values never need to be compared with raw strings.
  • IntEnum members are also ints. Use it when the values must work as numbers, such as priority levels that you sort.
  • StrEnum members are also strs. 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.
  • Flag members 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) in checks 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 False

Part 9's state pattern takes this idea further, with a class per state.

7. Choosing the right tool ​

NeedUse
Domain object with behaviour@dataclass
Immutable value, dict key@dataclass(frozen=True)
Millions of small records@dataclass(slots=True)
Small tuple-like resultNamedTuple
Shape of a JSON dictTypedDict
Fixed set of choicesEnum / StrEnum
Untrusted input to validatePydantic 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

  • @dataclass reads annotated fields and writes __init__, __repr__, __eq__ and __match_args__, generating source text and running it with exec. It does not validate types.
  • Mutable defaults are refused. Use field(default_factory=list). field also takes repr=False and compare=False. __post_init__ runs after __init__ for checks.
  • kw_only=True or _: KW_ONLY makes fields keyword-only, which fixes default-ordering errors in subclasses.
  • frozen=True makes a value object: no assignment, and a generated __hash__. slots=True removes __dict__. order=True adds comparisons. replace copies with changes, asdict converts recursively.
  • NamedTuple is a real tuple with names. TypedDict describes a dict's keys for type checkers only.
  • An enumeration (Enum, IntEnum, StrEnum, Flag) is built by the EnumType metaclass. Members are singletons, duplicates become aliases, and Status("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.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet