01A.6 Classes, Dataclasses and Enums
Up to now your ticket data has been plain dictionaries: {"id": "T-1", "subject": "...", "priority": 1}. Dictionaries are flexible, but they have no rules — nothing stops you writing "prompty" for "priority", nothing stops ticket["prompty"] from silently returning None-ish behaviour downstream, and nothing ties the data to the functions that work on it. This lesson introduces the three tools Python gives you for data with a shape and a vocabulary: classes (objects that bundle data with the methods that operate on it), dataclasses (a decorator that writes most of the boilerplate for you), and enums (named constants so "open" is never confused with "OPEN" or "0"). These are the same ideas every later module leans on: the SDKs return Pydantic objects (which are classes), tool definitions are classes, and statuses everywhere are enums.
What you'll learn
- What a class is, how
__init__andselfwork, and the difference between instance and class attributes (including the shared-mutable-attribute trap) - The dunder methods that make your objects print nicely, compare equal, sort, and behave like built-in containers:
__repr__,__str__,__eq__,__hash__,__lt__,__len__,__iter__,__getitem__,__contains__,__call__,__enter__/__exit__ @propertyfor computed attributes and validated setters;@classmethodand@staticmethod; "private" by convention;__slots__- Inheritance vs composition,
super(), the method resolution order (MRO), abstract base classes,typing.Protocolfor "if it quacks like a classifier", and when multiple inheritance hurts dataclassesin full:field(default_factory=...),frozen,order,kw_only,slots,__post_init__,asdict/astuple/replace, and the decision table againstNamedTuple,TypedDictand Pydanticenumin full:Enum,IntEnum,StrEnum,auto(),Flag/IntFlag, aliases,@unique,@verify, and why bare strings are a trap- Object design for real code: identity vs equality,
copyvsdeepcopy, introspection withvars/dir/getattr, when not to write a class, and the strategy/adapter/registry patterns you'll meet again
What you don't need
- Any prior object-oriented programming. If you've written
class Foo:in another language the "Coming from another stack" callouts map the differences; if not, everything is explained from zero. - Type hints in depth — this lesson uses them lightly (
def f(x: int) -> str) because they document intent; 01A.10 teaches them properly. - Exceptions in depth — you saw
try/exceptin 01A.3; this lesson only shows that exception classes are classes too. 01A.8 owns errors.
Setup
Everything in this lesson is pure standard library — no packages to install, no API key, no network. You need Python 3.11 or newer (3.13 or newer recommended; the current stable release is 3.15.x as of November 2026, and Python 3.10 reached end of life in October 2026). If you haven't set up Python yet, Module 00 walks through it; the short version is uv python install 3.13 and then uv run python file.py, or plain python3 file.py if Python is already on your PATH. Save the snippets as you go and run them — every Output: block below was produced by running exactly the code shown, on Python 3.14. The exception types and values are identical on 3.11–3.15, but a few error-message texts differ slightly on older versions (each is noted inline where it matters). Snippets accumulate within a part: a # name.py comment suggests a file name for the code shown so far, and snippets without one continue the definitions above them — keep each part's snippets together in one file (or paste them into one interpreter session) and the outputs reproduce.
What you must be able to do after this lesson#
- Write a class with init, self and a readable repr
- Explain instance and class attributes and the shared-mutable trap
- Choose between inheritance and composition
- Write a dataclass with defaults and frozen fields
- Use an Enum instead of bare strings
- Decide when not to write a class
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "The SDK returns Pydantic models, not dicts." | 3.8 Serialising dataclasses to JSON and 3.9's decision table |
"Define a Protocol for the model client so tests can fake it." |
2.5 typing.Protocol — structural typing |
| "Make the config a frozen dataclass." | 3.4 frozen, kw_only, slots and friends |
| "The tool registry maps names to callables." | 5.5 The patterns that matter: strategy, adapter, registry |
"Use an IntEnum for priority, a StrEnum for status." |
Part 4: enum |
"Two tickets are equal if their IDs match — implement __eq__ and __hash__." |
1.4 Printing and comparing |
| "Adapters translate canonical types to each provider's wire format." | 2.7 The LLM-shaped example |
"finish_reason is an enum on every provider." |
4.7 Enums in AI code |
| "Inject the classifier so tests can swap it." | 5.3 Dependency injection is "pass the thing in" |
Part 1: Classes — bundling data and behaviour#
1.1 Why classes exist#
In 01A.4 you modelled a ticket as a dict: {"id": "T-1", "subject": "Cannot log in", "priority": 1, "status": "open"}. That works, but the dict is just a bag of values. Three problems show up quickly in real code:
- No guard rails.
ticket["prompty"]is a typo that returns aKeyErrorat best and a silentNoneat worst. Nothing checks thatpriorityis anintbetween 1 and 5. - No behaviour attached. "Escalate this ticket" means "raise the priority number, set status to pending" — that rule has to live somewhere, and with dicts it lives in a free function that every caller must remember to use correctly.
- Strings where vocabularies belong.
statusis"open","OPEN","Open "or"0"depending on who wrote the row. A typo'd status silently fails every== "open"check.
A class is Python's answer: a blueprint that defines a kind of object with named attributes (the data) and methods (the functions that belong to it). An object created from a class is an instance. The class is the mould; each instance is a separate casting.
# ticket_handwritten.py — the long way, before dataclasses
class Ticket:
"""A support ticket, written the long way."""
registry = [] # class attribute: ONE list shared by every Ticket
def __init__(self, ticket_id: str, subject: str, priority: int = 3):
self.ticket_id = ticket_id
self.subject = subject
self.priority = priority
self.status = "open"
self.notes: list[str] = []
def describe(self) -> str:
return f"{self.ticket_id}: {self.subject} (priority {self.priority}, {self.status})"
def add_note(self, note: str) -> None:
self.notes.append(note)
t = Ticket("T-1042", "Cannot log in after password reset", priority=4)
t.add_note("Customer tried two browsers.")
t.add_note("Reset link expired after 15 minutes.")
print(t.describe())
print(t.notes)
print("type(t) ->", type(t))
print("type(t).__name__ ->", type(t).__name__)
print("vars(t) ->", vars(t))
print("registry shared? ->", t.registry is Ticket.registry)T-1042: Cannot log in after password reset (priority 4, open)
['Customer tried two browsers.', 'Reset link expired after 15 minutes.']
type(t) -> <class '__main__.Ticket'>
type(t).__name__ -> Ticket
vars(t) -> {'ticket_id': 'T-1042', 'subject': 'Cannot log in after password reset', 'priority': 4, 'status': 'open', 'notes': ['Customer tried two browsers.', 'Reset link expired after 15 minutes.']}
registry shared? -> True1.2 Anatomy: class, __init__, self#
Four pieces of syntax do all the work:
class Ticket:— declares the blueprint. The body is indented, exactly like a function body. The name isCamelCaseby convention (classes are "types", and types are capitalised).def __init__(self, ...)— the initialiser: the method Python calls when you writeTicket(...). Names wrapped in double underscores front and back (__init__,__repr__) are called dunder methods ("double underscore") or special methods — Python calls them implicitly in response to syntax likeTicket(...),print(t),t == u,len(t). You rarely call them directly.self— the first parameter of every instance method. It is just a name (you could call itthisorme); the conventionselfis universal.self.x = ...— assignment inside__init__(or any method) creates an instance attribute on that one object.
Two details worth internalising now:
__init__is not the constructor.Ticket("T-1", "...")first creates the empty object (__new__), then calls__init__on it to fill it in. You almost never write__new__.- Attributes spring into existence by assignment. There is no
public String subject;declaration line.self.subject = subjectboth declares and initialises. This is whyvars(t)shows exactly what an instance holds.
1.3 Instance attributes vs class attributes#
This is the single most common class bug in Python, so it deserves its own subsection.
- An attribute assigned on
selfinside a method (self.notes = []) belongs to that instance. Two tickets have two separatenoteslists. - An attribute assigned in the class body (
registry = []) belongs to the class itself — there is exactly one, shared by every instance that doesn't shadow it.
class Draft:
tags = [] # CLASS attribute: shared by all Drafts!
def __init__(self, title: str):
self.title = title
def add_tag(self, tag: str) -> None:
self.tags.append(tag)
d1 = Draft("Release notes")
d2 = Draft("Blog post")
d1.add_tag("python")
print("d2.tags (should be empty!) ->", d2.tags)d2.tags (should be empty!) -> ['python']d1.add_tag("python") appended to the class's list, so d2 sees it too. The fix is one line — initialise per instance:
class Draft:
def __init__(self, title: str):
self.title = title
self.tags: list[str] = [] # instance attribute: one list per Draft
def add_tag(self, tag: str) -> None:
self.tags.append(tag)Class attributes aren't evil — they're how you share immutable configuration (VERSION = "1.4", MAX_RETRIES = 3) or define methods. The rule of thumb: mutable class attributes are almost always a bug; immutable ones are fine.
1.4 Printing and comparing: __repr__, __str__, __eq__, __hash__#
Every object already has default versions of these — print(t) on a bare class shows something like <__main__.Ticket object at 0x10f2a3d50> (the address varies per run, which is why it's not worth pasting). The dunders let you replace them:
# ticket_dunders.py
from functools import total_ordering
@total_ordering
class Ticket:
def __init__(self, ticket_id: str, subject: str, priority: int = 3):
self.ticket_id = ticket_id
self.subject = subject
self.priority = priority
self.status = "open"
# repr is for developers (unambiguous, often copy-pasteable);
# str is for users. print() and f-strings use str().
def __repr__(self) -> str:
return (f"Ticket(ticket_id={self.ticket_id!r}, subject={self.subject!r}, "
f"priority={self.priority})")
def __str__(self) -> str:
return f"{self.ticket_id}: {self.subject}"
# Two tickets are "the same ticket" when id, subject and priority match.
def __eq__(self, other) -> bool:
if not isinstance(other, Ticket):
return NotImplemented
return (self.ticket_id, self.subject, self.priority) == \
(other.ticket_id, other.subject, other.priority)
# The contract: objects that compare equal MUST hash equal,
# so __hash__ is derived from the same fields __eq__ uses.
def __hash__(self) -> int:
return hash((self.ticket_id, self.subject, self.priority))
# Sort "most urgent first": higher priority number wins, ties by id.
def __lt__(self, other) -> bool:
if not isinstance(other, Ticket):
return NotImplemented
return (-self.priority, self.ticket_id) < (-other.priority, other.ticket_id)
a = Ticket("T-1042", "Cannot log in", priority=4)
b = Ticket("T-1042", "Cannot log in", priority=4)
c = Ticket("T-2001", "Invoice question", priority=1)
print("a == b ->", a == b, "| a is b ->", a is b)
print("a == c ->", a == c)
print("hash(a) == hash(b) ->", hash(a) == hash(b))
print("repr(a) ->", repr(a))
print("str(a) ->", str(a))
print("print() uses str:", a)
print("sorted ->", [t.ticket_id for t in sorted([c, a])])
print("a <= b ->", a <= b, "| c > a ->", c > a)a == b -> True | a is b -> False
a == c -> False
hash(a) == hash(b) -> True
repr(a) -> Ticket(ticket_id='T-1042', subject='Cannot log in', priority=4)
str(a) -> T-1042: Cannot log in
print() uses str: T-1042: Cannot log in
sorted -> ['T-1042', 'T-2001']
a <= b -> True | c > a -> TrueThe rules that matter:
__repr__vs__str__.repr()should be unambiguous and ideally valid-looking Python (Ticket(ticket_id='T-1042', ...));str()is for end users.print(), f-strings andstr()all use__str__; the REPL and containers like lists use__repr__for their elements — which is why[t]prints[Ticket(ticket_id=...)]even thoughprint(t)is pretty.__eq__needsisinstance, nottype() ==. ReturningNotImplementedfor foreign types lets Python try the reflected comparison (other.__eq__(self)) and finally fall back tois. Usingtype(other) is Ticketwould break comparisons with subclasses.__eq__without__hash__makes the object unhashable. Defining__eq__sets__hash__toNoneautomatically — a deliberate Python rule, because "equal objects must hash equal" is easy to get wrong. If your class is mutable you probably want it unhashable (its hash could change as fields mutate, corrupting dicts/sets). For value objects you'll makefrozendataclasses instead — see 3.4.total_orderingfills in<=,>,>=from your__lt__and__eq__. Write the two "hard" directions and let the decorator do the rest — but only when the ordering is a total order (every pair comparable), which is true for "sort by priority then id".
1.5 Making objects behave like built-ins#
Python's built-in types feel nice because they implement a small set of dunders. You can give your classes the same feel:
# board.py — a collection that quacks like a list
class TicketBoard:
"""A board of ticket ids that quacks like a list."""
def __init__(self, ids=()):
self._ids = list(ids)
def __len__(self) -> int:
return len(self._ids)
def __iter__(self):
return iter(self._ids)
def __getitem__(self, index):
return self._ids[index]
def __contains__(self, ticket_id) -> bool:
return ticket_id in self._ids
def __repr__(self) -> str:
return f"TicketBoard({self._ids!r})"
board = TicketBoard(["T-1", "T-2", "T-3"])
print("len(board) ->", len(board))
print("board[1] ->", board[1])
print("'T-2' in board ->", "T-2" in board)
print("list(board) ->", list(board))
print("board[::-1] ->", board[::-1]) # slicing works via __getitem__len(board) -> 3
board[1] -> T-2
'T-2' in board -> True
list(board) -> ['T-1', 'T-2', 'T-3']
board[::-1] -> ['T-3', 'T-2', 'T-1']Each dunder maps to syntax: len(x) → __len__, for i in x/list(x) → __iter__, x[i] → __getitem__, a in x → __contains__. Delegating to an inner list (here self._ids) is the standard trick — you're not reimplementing a list, just giving it a domain meaning and extra methods.
__call__ makes an instance callable like a function — useful for strategy objects and small functors:
class KeywordFilter:
def __init__(self, keyword: str):
self.keyword = keyword.lower()
def __call__(self, subject: str) -> bool:
return self.keyword in subject.lower()
subjects = ["Cannot log in", "Invoice question", "Login page is slow"]
login_only = KeywordFilter("login")
print("callable(login_only) ->", callable(login_only))
print("filter ->", [s for s in subjects if login_only(s)])callable(login_only) -> True
filter -> ['Login page is slow']Note "Cannot log in" does not match "login" — substring matching is literal; real keyword matching needs word boundaries (a regex from 01A.2, or the classifier in Part 6 which matches "log in" and "login" separately).
1.6 @property — computed attributes and validation#
@property lets a method be used like an attribute: c.display_name instead of c.display_name(). Two uses:
- Computed attributes — derive a value from other fields without storing it (and without it going stale).
- Validated setters — intercept assignment so
c.email = "junk"raises instead of storing junk.
class Customer:
def __init__(self, name: str, email: str):
self.name = name
self.email = email # goes through the setter
@property
def email(self) -> str:
return self._email
@email.setter
def email(self, value: str) -> None:
if "@" not in value:
raise ValueError(f"not an email address: {value!r}")
self._email = value
@property
def display_name(self) -> str:
return f"{self.name} <{self._email}>"
c = Customer("Priya", "priya@example.com")
print("display_name ->", c.display_name)
try:
c.email = "not-an-email"
except ValueError as e:
print("setter rejected ->", e)display_name -> Priya <priya@example.com>
setter rejected -> not an email address: 'not-an-email'The getter/setter pair shares one name (email); the real storage is self._email. Callers can't tell the difference between c.email the attribute and c.email the property — that's the point. Properties are not free: they're computed on every access, so don't put expensive work in one. If a computed value is expensive and stable, functools.cached_property computes it once and caches the result on the instance — at the cost of needing a per-instance __dict__ to store the result in, so it does not work on a __slots__ class (which has none).
1.7 @classmethod and @staticmethod#
Three kinds of methods live in a class body:
- Instance methods take
self— the default, used above. @classmethodtakescls(the class itself) as first arg — for alternative constructors and factory methods that must returncls(...)so subclasses get the right type.@staticmethodtakes neither — a plain function namespaced inside the class for cohesion.
class Ticket:
def __init__(self, ticket_id: str, subject: str):
self.ticket_id = ticket_id
self.subject = subject
self._priority = 3 # "private" by convention
self.__cache = {} # name-mangled: really _Ticket__cache
@classmethod
def from_dict(cls, data: dict):
# cls is the class itself — works for subclasses too.
return cls(data["ticket_id"], data["subject"])
@staticmethod
def clamp_priority(p: int) -> int:
# No self, no cls: just a namespaced function.
return max(1, min(5, p))
t = Ticket.from_dict({"ticket_id": "T-9", "subject": "Where is my order?"})
print("from_dict ->", t.ticket_id, t.subject)
print("clamp ->", Ticket.clamp_priority(9), Ticket.clamp_priority(-2))from_dict -> T-9 Where is my order?
clamp -> 5 1from_dict is the pattern you'll use constantly: data arrives as dicts/JSON (every API response), and a classmethod is the clean place to translate dict -> Ticket.
1.8 "Private" by convention: _x and __x#
Python has no private/protected/public enforcement. The convention:
self._priority— single leading underscore: "internal, don't touch from outside". Nothing stops you; it's a request, not a wall. The single underscore also tells linters, documentation tools andfrom module import *(which skips such names at module level) to treat it as internal.self.__cache— double leading underscore (and at most one trailing) triggers name mangling: the attribute is stored as_Ticket__cache, making accidental collisions in subclasses unlikely. It is still accessible ast._Ticket__cache— mangling is anti-accident, not security.
# continues 1.7 — uses that Ticket class (it has _priority and __cache)
t2 = Ticket("T-1", "hello")
print("t2._priority readable ->", t2._priority)
try:
print(t2.__cache)
except AttributeError as e:
print("t2.__cache ->", type(e).__name__, e)
print("mangled name works ->", t2._Ticket__cache)t2._priority readable -> 3
t2.__cache -> AttributeError 'Ticket' object has no attribute '__cache'
mangled name works -> {}1.9 __slots__ awareness#
By default every instance carries a __dict__ — a per-object dictionary holding its attributes. __slots__ replaces it with a fixed set of named slots:
class Slotted:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
s = Slotted(1, 2)
print("hasattr __dict__ (slotted) ->", hasattr(s, "__dict__"))
try:
s.z = 3
except AttributeError as e:
print("s.z = 3 ->", type(e).__name__, e)hasattr __dict__ (slotted) -> False
s.z = 3 -> AttributeError 'Slotted' object has no attribute 'z' and no __dict__ for setting new attributes(On Python 3.11–3.12 the AttributeError message ends at 'z' — the and no __dict__ for setting new attributes suffix was added in 3.13.)
Benefits: smaller memory footprint and faster attribute access — meaningful when you have millions of instances (embeddings-adjacent data structures, big eval sets). Costs: no __dict__, so no dynamic attributes, vars() doesn't work, and weak references need weakref_slot=True on a dataclass (3.11+). One more caveat: __slots__ only binds the class that declares it — a slotted class inheriting from an unslotted base still gets a __dict__ from the base, so the saving only fully applies when every class in the hierarchy is slotted. You will rarely need __slots__ — dataclasses offer slots=True (3.4) when you do.
1.10 Context-manager dunders: __enter__/__exit__ (preview)#
Any object with __enter__ and __exit__ can be used in with. The protocol: __enter__ runs on the way in and its return value is bound to as x; __exit__ runs on the way out even if an exception flew, and returning True swallows the exception.
class Swallow:
"""A tiny context manager that optionally swallows an exception type."""
def __init__(self, exc_type):
self.exc_type = exc_type
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
# Return True -> Python pretends nothing went wrong.
return exc_type is not None and issubclass(exc_type, self.exc_type)
print("before with-block")
with Swallow(ValueError):
raise ValueError("simulated failure")
print("after with-block (exception was swallowed)")before with-block
after with-block (exception was swallowed)That's the whole protocol — files, locks and timers are all just classes implementing it. 01A.8 teaches context managers properly; the point here is that with is class machinery, not magic.
Part 2: Inheritance, composition and interfaces#
2.1 Inheritance: subclassing, super(), overriding#
Inheritance lets a new class reuse and extend an existing one: class VipTicket(Ticket) means "a VIP ticket is a ticket, with extras". The subclass inherits all attributes and methods, can override any of them, and calls the parent's version explicitly with super().
# vip.py
class Ticket:
def __init__(self, ticket_id: str, subject: str, priority: int = 3):
self.ticket_id = ticket_id
self.subject = subject
self.priority = priority
self.status = "open"
def describe(self) -> str:
return f"{self.ticket_id}: {self.subject} (p{self.priority}, {self.status})"
def escalate(self) -> None:
self.priority = min(5, self.priority + 1)
self.status = "pending"
class VipTicket(Ticket):
def __init__(self, ticket_id: str, subject: str, account_tier: str = "gold"):
super().__init__(ticket_id, subject, priority=4) # reuse the parent's setup
self.account_tier = account_tier
def describe(self) -> str:
# super() lets you extend the parent's answer instead of copying it.
return f"{super().describe()} [{self.account_tier} VIP]"
v = VipTicket("T-7", "Charged twice", account_tier="platinum")
print("v.describe() ->", v.describe())
v.escalate()
print("after escalate ->", v.describe())
print("isinstance(v, Ticket) ->", isinstance(v, Ticket))
print("MRO ->", [c.__name__ for c in VipTicket.__mro__])v.describe() -> T-7: Charged twice (p4, open) [platinum VIP]
after escalate -> T-7: Charged twice (p5, pending) [platinum VIP]
isinstance(v, Ticket) -> True
MRO -> ['VipTicket', 'Ticket', 'object']Three things to notice:
VipTicket(...)calls the subclass__init__, which callssuper().__init__(...)to reuse the parent's setup, then adds its own field. If the subclass doesn't define__init__at all, it inherits the parent's verbatim.v.escalate()resolves toTicket.escalate— inherited, not copied.isinstance(v, Ticket)isTrue: a subclass instance is an instance of the parent. This is what makes polymorphism work — a function expecting aTicketaccepts aVipTicket.
2.2 The method resolution order (MRO)#
When a class has several ancestors, "which method wins?" is answered by the method resolution order: a linearisation computed by the C3 algorithm. You never compute it by hand — ClassName.__mro__ prints it, and super() inside a method walks one step along it.
# diamond.py
class A:
def who(self) -> str:
return "A"
class B(A):
def who(self) -> str:
return "B+" + super().who()
class C(A):
def who(self) -> str:
return "C+" + super().who()
class D(B, C):
pass
print("D().who() ->", D().who())
print("D MRO ->", [c.__name__ for c in D.__mro__])D().who() -> B+C+A
D MRO -> ['D', 'B', 'C', 'A', 'object']flowchart TB
D["class D(B, C)"] --> B["class B(A)"]
D --> C["class C(A)"]
B --> A["class A"]
C --> A
A --> O["object"]Read the MRO list left to right: D → B → C → A → object. D().who() finds B.who first; B's super() doesn't mean "the parent" — it means "the next class in this instance's MRO", which is C, then A. That's why cooperative multiple inheritance (each method calling super()) produces B+C+A: every layer gets to add its piece. This is exactly how mixins and frameworks like Django's model classes work.
2.3 When inheritance is the wrong tool: composition#
The test for inheritance is the "is-a" test: a VipTicket is a Ticket, so inheritance fits. But "has-a" relationships want composition — the class holds another object:
# Sketch only — Ticket, Logger, Notifier and TicketStore are placeholders;
# this illustrates the shape, it is not meant to run.
# Bad: a ticket is not a logger, a notifier AND a store
class EverythingTicket(Ticket, Logger, Notifier, TicketStore):
pass
# Good: a ticket HAS a customer, a store HAS tickets, a report USES a classifier
class Report:
def __init__(self, tickets, classifier):
self.tickets = tickets # composition: holds what it needs
self.classifier = classifierComposition wins almost every time in AI code because:
- It survives change. If
TicketStore's interface changes, only the store breaks — not every class that inherited from it. - It composes at runtime. You can swap
KeywordClassifierforLengthClassifierby passing a different object — no subclass needed (that's dependency injection, and it's how the provider adapters in 03.11 plug in). - Python's single inheritance is fine — the guideline "prefer composition over inheritance" exists because MI is where Python's sharpest edges live (next two sections).
A useful mental model: inheritance is for "is-a" type hierarchies (rare in app code); composition is for "has-a"/"uses-a" wiring (everywhere). Dataclasses made the "record" case so cheap that deep class hierarchies are rarely worth it.
2.4 Abstract base classes (abc)#
An abstract base class defines an interface — methods subclasses must implement — and refuses to be instantiated itself. abc.ABC plus @abstractmethod:
# classifier_abc.py
from abc import ABC, abstractmethod
class Classifier(ABC):
@abstractmethod
def classify(self, ticket) -> str:
"""Return a label like 'billing' or 'technical'."""
try:
Classifier()
except TypeError as e:
print("Classifier() ->", type(e).__name__, ":", e)
class KeywordClassifier(Classifier):
def __init__(self, keywords: dict[str, tuple[str, ...]]):
self.keywords = keywords
def classify(self, ticket) -> str:
text = ticket.subject.lower()
for label, words in self.keywords.items():
if any(w in text for w in words):
return label
return "general"
class Ticket:
def __init__(self, subject: str):
self.subject = subject
kc = KeywordClassifier({"billing": ("invoice", "charge", "refund"),
"login": ("log in", "login", "password")})
print("kc.classify ->", kc.classify(Ticket("Charged twice on my invoice")))
print("kc is a Classifier ->", isinstance(kc, Classifier))Classifier() -> TypeError : Can't instantiate abstract class Classifier without an implementation for abstract method 'classify'
kc.classify -> billing
kc is a Classifier -> True(On Python 3.11 the same error uses the older wording Can't instantiate abstract class Classifier with abstract method classify — the "without an implementation for" phrasing arrived in 3.12.)
The TypeError at instantiation is the payoff: you cannot forget to implement classify — Python stops you at Classifier()-shaped mistakes. ABCs also give you isinstance checks and a place to hang shared concrete methods (a describe() that calls self.classify()).
2.5 typing.Protocol — structural typing#
ABC requires inheritance: KeywordClassifier(Classifier) must say so. typing.Protocol flips it — a class is a classifier if it has the right method, whether or not it ever heard of Classifier. Python calls this structural typing ("if it quacks like a classifier, it is one").
# protocol_demo.py
from typing import Protocol, runtime_checkable
@runtime_checkable
class TicketClassifier(Protocol):
def classify(self, ticket) -> str: ...
class LengthClassifier:
"""Does NOT inherit from anything — it just has the right method."""
def classify(self, ticket) -> str:
return "quick" if len(ticket.subject) < 30 else "needs-review"
class Ticket:
def __init__(self, subject: str):
self.subject = subject
lc = LengthClassifier()
print("isinstance(lc, TicketClassifier) ->", isinstance(lc, TicketClassifier))
print("isinstance(object(), TicketClassifier) ->", isinstance(object(), TicketClassifier))
print("lc.classify ->", lc.classify(Ticket("short")))isinstance(lc, TicketClassifier) -> True
isinstance(object(), TicketClassifier) -> False
lc.classify -> quickThree rules to remember:
@runtime_checkableis required forisinstance/issubclassagainst a Protocol — without it,isinstanceraisesTypeError. (Static type checkers like pyright/mypy check Protocols without the decorator; the decorator is only for runtime checks.)- Runtime checks are shallow.
isinstanceverifies the method names exist, not their signatures.def classify(self) -> intwith wrong args still passes. Real contract enforcement is the type checker's job — 01A.10 covers that. - Protocols describe the consumer's needs. Define the smallest interface the caller requires —
classify(ticket) -> str— not the implementation's full API. This is why later lessons defineEmbedder,RetrieverandChatModelprotocols (06.1, 03.10) — so fakes can be swapped in tests.
2.6 Mixins and multiple-inheritance warnings#
A mixin is a small class meant to be combined with others, contributing one capability:
# continues vip.py — Ticket is defined there
class Timestamped:
def stamp(self) -> str:
return f"{self.ticket_id}@handled"
class LoggedTicket(Timestamped, Ticket):
pass
lt = LoggedTicket("T-3", "App crashes on save")
print("lt.stamp() ->", lt.stamp())
print("LoggedTicket MRO ->", [c.__name__ for c in LoggedTicket.__mro__])lt.stamp() -> T-3@handled
LoggedTicket MRO -> ['LoggedTicket', 'Timestamped', 'Ticket', 'object']Mixins work because they're tiny and orthogonal (Timestamped doesn't care what else the class is). The warnings:
- Diamond surprises. Two parents both overriding the same method → the MRO decides silently. If you can't predict
D().who()from the class list, don't use MI. super()in mixins must be cooperative — every method callssuper()so the chain reaches every layer (2.2). A mixin that doesn't callsuper()silently cuts the chain for classes placed after it.- MI is for capabilities, not types.
class Report(Ticket, Customer)is nonsense — a report isn't a ticket. If you can't say "X is a Y" for each parent, use composition.
2.7 The LLM-shaped example: a Provider interface#
Here's the pattern you'll meet throughout the path, previewed honestly. Provider SDKs all speak different APIs, so 03.11 builds a provider-agnostic client: canonical types in your code, one adapter per provider translating to/from each wire format. The seam is exactly what you've just learned — a Protocol (or ABC) plus composition:
# preview only — 03.11 owns the real thing
from typing import Protocol
class ChatModel(Protocol):
"""Anything that can complete a chat, however it does it."""
def complete(self, messages: list[dict]) -> str: ...
class FakeChat:
"""Test double: returns canned text, no network, no key."""
def complete(self, messages: list[dict]) -> str:
return "This is a scripted reply."
def answer(model: ChatModel, messages: list[dict]) -> str:
return model.complete(messages)
print(answer(FakeChat(), [{"role": "user", "content": "hi"}]))This is a scripted reply.answer() never knows whether it got OpenAI, Anthropic, Gemini or the fake — that's the whole point of the Protocol + adapter design in 03.11 Part 4, and the same trick powers the ScriptedModel/ScriptedBackend fakes used for testing LLM code without keys (03.10).
Part 3: dataclasses#
3.1 The problem they solve#
Look back at Ticket in 1.4: four dunders, ~30 lines, and the only real content is "these six fields exist". Most classes you'll write for AI work are exactly that — a bag of typed fields plus maybe one or two methods. Writing __init__, __repr__, __eq__ by hand for every one is boilerplate that hides the actual design.
A dataclass is a class decorated with @dataclass: you declare the fields as annotated class attributes, and Python generates __init__, __repr__, __eq__ (and optionally ordering and hashing) for you. It arrived in Python 3.7 (PEP 557) and is now the default way to write a data-carrying class.
# ticket_dc.py
import json
from dataclasses import asdict, astuple, dataclass, field, fields, replace
@dataclass
class Ticket:
ticket_id: str
subject: str
priority: int = 3
status: str = "open"
tags: list[str] = field(default_factory=list) # fresh list per instance
notes: list[str] = field(default_factory=list)
def describe(self) -> str:
return f"{self.ticket_id}: {self.subject}"
t1 = Ticket("T-1", "Cannot log in", priority=4)
t2 = Ticket("T-1", "Cannot log in", priority=4)
print("t1 == t2 ->", t1 == t2, "| t1 is t2 ->", t1 is t2)
t1.tags.append("urgent")
t2.tags.append("vip")
print("t1.tags ->", t1.tags, "| t2.tags ->", t2.tags) # NOT shared
print("eq compares every field, tags included ->", t1 == t2)
print("repr(t1) ->", repr(t1))
print("str via print:")
print(" ", t1.describe())
print("asdict(t1) ->", asdict(t1))
print("json.dumps(asdict(t1)) ->", json.dumps(asdict(t1)))
print("astuple(t1)[:3] ->", astuple(t1)[:3])
print("field names ->", [f.name for f in fields(Ticket)])
t3 = replace(t1, priority=2, status="pending")
print("replace ->", repr(t3))t1 == t2 -> True | t1 is t2 -> False
t1.tags -> ['urgent'] | t2.tags -> ['vip']
eq compares every field, tags included -> False
repr(t1) -> Ticket(ticket_id='T-1', subject='Cannot log in', priority=4, status='open', tags=['urgent'], notes=[])
str via print:
T-1: Cannot log in
asdict(t1) -> {'ticket_id': 'T-1', 'subject': 'Cannot log in', 'priority': 4, 'status': 'open', 'tags': ['urgent'], 'notes': []}
json.dumps(asdict(t1)) -> {"ticket_id": "T-1", "subject": "Cannot log in", "priority": 4, "status": "open", "tags": ["urgent"], "notes": []}
astuple(t1)[:3] -> ('T-1', 'Cannot log in', 4)
field names -> ['ticket_id', 'subject', 'priority', 'status', 'tags', 'notes']
replace -> Ticket(ticket_id='T-1', subject='Cannot log in', priority=2, status='pending', tags=['urgent'], notes=[])Read that carefully — one decorator replaced __init__, __repr__, __eq__ and gave you asdict, astuple, replace, fields on top. t1 == t2 was True before the appends because every field matched; after t1.tags and t2.tags diverged it became False — dataclass equality compares all fields, including mutable ones. Keep that in mind: two tickets with different note lists are not equal.
3.2 Fields, defaults and default_factory#
A field is a class-level annotation: ticket_id: str declares "instances have a ticket_id that is a str". Two rules:
- Fields with defaults must come after fields without — same rule as function parameters, enforced at class creation:
from dataclasses import dataclass
try:
@dataclass
class Bad:
a: int = 1
b: int # non-default after default
except TypeError as e:
print(type(e).__name__, ":", e)TypeError : non-default argument 'b' follows default argument 'a'(On Python 3.11–3.12 the message ends at default argument — the offending field's name 'a' was appended in 3.13.)
- Mutable defaults are rejected.
tags: list = []raisesValueErrorat decoration time — the same shared-mutable trap from 1.3, now caught for you:
try:
@dataclass
class Bad:
name: str
tags: list = []
except ValueError as e:
print(type(e).__name__, ":", e)ValueError : mutable default <class 'list'> for field tags is not allowed: use default_factoryThe fix is field(default_factory=list): default_factory is a zero-argument callable invoked once per instance, so each ticket gets its own list. Use it for any mutable default (list, dict, set) — and for expensive immutable ones too (field(default_factory=lambda: compute_default())).
@dataclass
class Ticket:
ticket_id: str
subject: str
tags: list[str] = field(default_factory=list) # fresh list per instance
meta: dict = field(default_factory=dict)Two more field tools worth knowing:
field(init=False)— the field exists on instances but isn't an__init__parameter (computed in__post_init__, below).field(compare=False)/field(repr=False)— exclude a field from__eq__/ordering or fromrepr(useful for caches and large blobs).ClassVar— annotate a fieldClassVar[int]and it's not a dataclass field at all: it stays a plain class attribute (shared). This is how you declare class-level constants on a dataclass without them becoming per-instance init params.InitVar— a pseudo-field passed to__init__and__post_init__but not stored (e.g., a password you validate then discard).field(metadata={...})— attach arbitrary key-value data to a field declaration; tools that introspect fields (ORMs, serializers, your ownfields()walks) read it.
InitVar in action — the password is checked at construction and never stored:
from dataclasses import InitVar, dataclass
@dataclass
class Signup:
email: str
password: InitVar[str] # init-only: validated, never stored
def __post_init__(self, password: str) -> None:
if len(password) < 8:
raise ValueError("password too short")
s = Signup("a@b.com", "correct horse")
print("fields stored ->", vars(s)) # password is NOT here
try:
Signup("a@b.com", "short")
except ValueError as e:
print("rejected ->", e)fields stored -> {'email': 'a@b.com'}
rejected -> password too short3.3 The generated methods — and their hash rules#
@dataclass parameters control what gets generated:
| Parameter | Default | Generates |
|---|---|---|
init |
True |
__init__ from the fields |
repr |
True |
__repr__ showing ClassName(field=value, ...) |
eq |
True |
__eq__ comparing all fields (as a tuple, historically; field-by-field since 3.13) |
order |
False |
__lt__, __le__, __gt__, __ge__ — compares as a tuple of fields in declaration order |
unsafe_hash |
False |
__hash__ rules below |
frozen |
False |
blocks __setattr__/__delattr__ after init |
match_args |
True |
__match_args__ tuple for match statements (3.10+) |
kw_only |
False |
all __init__ params keyword-only (3.10+) |
slots |
False |
generates __slots__, returns a new class (3.10+) |
weakref_slot |
False |
adds '__weakref__' to __slots__ (3.11+) |
The hash rules (memorise these — they're the most-asked dataclass question): __hash__ is added only when it's safe:
eq=True, frozen=True→__hash__generated (immutable + equal ⇒ safe to hash).eq=True, frozen=False→__hash__ = None→ unhashable (mutable ⇒ hash could change while in a dict).eq=False→__hash__untouched (inheritsobject's identity hash — but then==is identity too, consistent).
So the default mutable dataclass can't go in a set or be a dict key — by design. If you need that, make it frozen=True (the value object pattern: Money, Point, Embedding-like records) or pass unsafe_hash=True when you know the fields won't mutate in practice.
One more generated dunder worth knowing: __match_args__ (on by default via match_args=True, 3.10+) lets the match statement from 01A.3 destructure a dataclass positionally:
from dataclasses import dataclass
@dataclass
class Point:
x: int
y: int
p = Point(3, 4)
print("match args ->", Point.__match_args__)
match p:
case Point(0, 0):
print("origin")
case Point(x, y) if x == y:
print("on the diagonal")
case Point(x=px, y=py):
print(f"ordinary point ({px}, {py})")match args -> ('x', 'y')
ordinary point (3, 4)Point(0, 0) and Point(x, y) are positional patterns — they bind fields in __match_args__ order; Point(x=px, y=py) uses keyword patterns and works regardless. Pass match_args=False (or reorder fields) when positional matching would be misleading — and note kw_only=True dataclasses still get __match_args__, but the positional patterns then bind by position, not by keyword.
3.4 frozen, kw_only, slots and friends#
Three flags cover most production needs:
from dataclasses import dataclass
# frozen + order
@dataclass(frozen=True, order=True)
class Rank:
priority: int
ticket_id: str
ranks = sorted([Rank(3, "T-9"), Rank(1, "T-2"), Rank(1, "T-1")])
print("sorted ranks ->", ranks)
print("Rank(1,'T-1') < Rank(1,'T-2') ->", Rank(1, "T-1") < Rank(1, "T-2"))
try:
ranks[0].priority = 9
except Exception as e:
print("frozen assign ->", type(e).__name__)
# kw_only
@dataclass(kw_only=True)
class Settings:
name: str
retries: int = 3
print("kw_only ->", Settings(name="triage", retries=5))
try:
Settings("triage", 5)
except TypeError as e:
print("positional ->", type(e).__name__, ":", str(e).splitlines()[0])
# slots
@dataclass(slots=True)
class Point:
x: int
y: int
p = Point(1, 2)
print("slots has __dict__ ->", hasattr(p, "__dict__"), "| __slots__ ->", p.__slots__)sorted ranks -> [Rank(priority=1, ticket_id='T-1'), Rank(priority=1, ticket_id='T-2'), Rank(priority=3, ticket_id='T-9')]
Rank(1,'T-1') < Rank(1,'T-2') -> True
frozen assign -> FrozenInstanceError
kw_only -> Settings(name='triage', retries=5)
positional -> TypeError : Settings.__init__() takes 1 positional argument but 3 were given
slots has __dict__ -> False | __slots__ -> ('x', 'y')What each buys you:
frozen=Truemakes the instance immutable — assignment raisesFrozenInstanceError. Combined witheq=Trueyou get a hashable value object: perfect forMoney,Point, config objects, and anything you'll put in aset/dict key or pass across a process boundary. Notefrozenis shallow: a frozen dataclass holding alistfield can still have that list mutated (f.tags.append(...)works!). True deep immutability needs tuples/MappingProxyTypeor Pydantic's frozen models.order=Truegenerates all four ordering dunders, comparing fields in declaration order — declare the most significant field first (prioritybeforeticket_id), or sorting won't do what you expect.kw_only=True(3.10+) forces keyword arguments —Settings(name="x", retries=5). Great for configs with several same-typed fields where positional order is a bug farm.slots=Truegives you the 1.9 benefits automatically: no__dict__, smaller, faster. Caveat: it returns a new class object, so class-level attributes defined after decoration behave subtly, and__post_init__can't add new attributes (there's no__dict__to absorb them).
3.5 __post_init__ — validation after construction#
__post_init__(self) runs at the end of the generated __init__ — the place for validation and derived fields:
from dataclasses import dataclass
@dataclass
class ValidatedTicket:
ticket_id: str
priority: int
def __post_init__(self) -> None:
if not 1 <= self.priority <= 5:
raise ValueError(f"priority must be 1-5, got {self.priority}")
try:
ValidatedTicket("T-9", 9)
except ValueError as e:
print("post_init ->", type(e).__name__, ":", e)
print("ok ->", ValidatedTicket("T-9", 2))post_init -> ValueError : priority must be 1-5, got 9
ok -> ValidatedTicket(ticket_id='T-9', priority=2)This is dataclass's answer to "validate at the boundary": construction is the one funnel every instance passes through, so a check here can't be bypassed by a later ticket.priority = 99 — wait, it can, because __post_init__ only runs at init. For ongoing enforcement you need frozen=True (can't mutate at all) or properties with setters (1.6). The honest layering: __post_init__ for construction-time invariants, frozen for immutability, Pydantic for boundary validation — which is exactly the split 01B.6 formalises.
3.6 asdict, astuple, replace, fields#
The module-level helpers round out the toolkit:
asdict(t)— deep-ish copy of the instance as a plaindict(recurses into dataclass fields, dicts, lists, tuples). This is your JSON-serialisation bridge:json.dumps(asdict(t)).astuple(t)— same idea as a tuple.replace(t, priority=2)— a new instance with some fields swapped; unchanged fields are passed through (mutable fields are shared, not copied —t3.tags is t1.tags!). For "update a record" semantics it's exactly right; just know the sharing.fields(Ticket)— introspect the field definitions (f.name,f.type,f.default,f.default_factory) — what serializers and ORMs use.is_dataclass(x)—Truefor dataclass instances and classes.
3.7 Inheritance#
Dataclasses inherit like normal classes — fields are collected base-first, and the generated __init__ includes parent fields before child fields:
from dataclasses import dataclass
@dataclass
class Ticket:
ticket_id: str
subject: str
priority: int = 3
@dataclass
class VipTicket(Ticket):
account_tier: str = "gold"
print("vip ->", VipTicket("T-7", "Charged twice"))
print("isinstance(vip, Ticket) ->", isinstance(VipTicket("T-7", "x"), Ticket))vip -> VipTicket(ticket_id='T-7', subject='Charged twice', priority=3, account_tier='gold')
isinstance(vip, Ticket) -> TrueTwo gotchas:
- Non-default-after-default applies across the hierarchy. If the base has
priority: int = 3and the subclass addsaccount_tier: strwithout a default →TypeErrorat class creation. Give the subclass field a default, or make base fields keyword-only (kw_only=True). - Every class in the chain needs
@dataclass. A plain (non-dataclass) base's__init__won't know about dataclass fields; mix them only when you know what you're doing.
3.8 Serialising dataclasses to JSON#
json.dumps doesn't know dataclasses — but asdict bridges it. Using the three-field Ticket from 3.7 (the one without tags/notes):
import json
raw = '{"ticket_id": "T-55", "subject": "Where is my parcel?", "priority": 2}'
loaded = Ticket(**json.loads(raw))
print("json round trip ->", loaded)json round trip -> Ticket(ticket_id='T-55', subject='Where is my parcel?', priority=2)Ticket(**dict) works because the generated __init__ parameter names are the field names — JSON keys map straight onto them. Round-tripping back out is json.dumps(asdict(t)). Three edge cases to know:
- Nested dataclasses:
asdictrecurses — aTicketholding aCustomerdataclass becomes nested dicts automatically. - Enum fields:
asdictleaves enum members in place.StrEnum/IntEnumserialise fine (they arestr/int); plainEnummembers raiseTypeError. Part 4 covers why. - Non-JSON types:
datetime,Decimal,setneed adefault=hook onjson.dumps(01A.9 owns JSON properly) — ordataclasses.asdictfirst, then clean the dict.
3.9 dataclass vs NamedTuple vs TypedDict vs Pydantic#
Four ways to say "a record with named fields" — the decision table:
dataclass |
NamedTuple |
TypedDict |
Pydantic BaseModel |
|
|---|---|---|---|---|
| What it is | A real class | A tuple subclass | A dict with typed keys |
A validated model class |
| Mutable? | Yes (unless frozen) |
No — immutable tuple | Yes (it's a dict) | Configurable |
| Methods allowed? | Yes | Yes (but no new fields) | No — dict only | Yes |
| Validation? | Only what you write | None | None (type checkers only) | Built-in, at runtime |
| JSON Schema? | Manual | Manual | Via type checkers | model_json_schema() |
| Use when | Internal data + behaviour | Small immutable record returned from a function | JSON-shaped dicts you don't want to convert | Anything crossing a boundary: API responses, config, tool args |
The rule of thumb for this path: dataclasses for your own internal objects; Pydantic for anything that crosses a boundary (API payloads, config files, structured model output). 03.1 §8.3 shows that every provider SDK's response objects are Pydantic models; 03.4 uses them as the schema language for structured output; 01B.6 teaches Pydantic properly. TypedDict appears in 01A.10 for typing JSON-shaped dicts; NamedTuple you'll meet in the stdlib tour (01A.7) — know it exists, prefer dataclasses.
flowchart TD
Q{"What are you modelling?"}
Q -- "a fixed vocabulary" --> E["enum"]
Q -- "a JSON-shaped dict<br/>you won't convert" --> T["TypedDict (01A.10)"]
Q -- "data crossing a boundary<br/>(API, config, model output)" --> V{"Needs runtime<br/>validation?"}
V -- "yes" --> P["Pydantic BaseModel (01B.6)"]
V -- "no" --> I{"Immutable tiny record?"}
I -- "yes" --> N["NamedTuple or frozen dataclass"]
I -- "no / needs methods" --> DC["@dataclass"]
Q -- "internal object<br/>with behaviour" --> DCPart 4: enum#
4.1 Why not bare strings#
Your Ticket.status is a str. Sooner or later someone writes "Open", "open ", "0" or "resolved!" — and every status == "open" check silently misses it. Strings have no vocabulary: any string is legal, typos are invisible until production. An enum fixes this by making the legal values named members of a class: Status.OPEN is one specific object, comparable, iterable and typo-proof (Status.OPNE is an AttributeError at write time, not a silent bug at runtime).
# enums.py
from enum import Enum, IntEnum, StrEnum, auto
class Status(StrEnum):
OPEN = "open"
PENDING = "pending"
RESOLVED = "resolved"
CLOSED = "closed"
class Priority(IntEnum):
LOW = 1
NORMAL = 2
HIGH = 3
URGENT = 4
class Department(Enum):
BILLING = auto() # 1
TECHNICAL = auto() # 2
GENERAL = auto() # 3
class Channel(StrEnum):
EMAIL = auto() # "email" — StrEnum auto() lowercases the name
CHAT = auto() # "chat"
s = Status.OPEN
print("s ->", s, "| repr ->", repr(s), "| .value ->", s.value)
print("s == 'open' ->", s == "open", "| isinstance(s, str) ->", isinstance(s, str))
print("str(Status.PENDING) ->", str(Status.PENDING))
print("Department.BILLING ->", Department.BILLING, "| value ->", Department.BILLING.value)
print("auto StrEnum ->", Channel.EMAIL, "|", Channel.CHAT.value)
print("Priority.NORMAL < Priority.HIGH ->", Priority.NORMAL < Priority.HIGH)
print("Priority.HIGH + 1 ->", Priority.HIGH + 1) # it's an int!
print("Priority(4) ->", repr(Priority(4)), "| Priority['HIGH'] ->", repr(Priority["HIGH"]))
print("list(Status) ->", list(Status)) # definition order
print("Status('pending') ->", Status("pending"))
print("Status.OPEN in Status ->", Status.OPEN in Status)s -> open | repr -> <Status.OPEN: 'open'> | .value -> open
s == 'open' -> True | isinstance(s, str) -> True
str(Status.PENDING) -> pending
Department.BILLING -> Department.BILLING | value -> 1
auto StrEnum -> email | chat
Priority.NORMAL < Priority.HIGH -> True
Priority.HIGH + 1 -> 4
Priority(4) -> <Priority.URGENT: 4> | Priority['HIGH'] -> <Priority.HIGH: 3>
list(Status) -> [<Status.OPEN: 'open'>, <Status.PENDING: 'pending'>, <Status.RESOLVED: 'resolved'>, <Status.CLOSED: 'closed'>]
Status('pending') -> pending
Status.OPEN in Status -> TrueThe vocabulary you need:
- Members are the named constants (
Status.OPEN); each has.name("OPEN") and.value("open"). - Lookup both ways:
Status("pending")finds by value,Status["PENDING"]by name. An unknown value raisesValueError—Status("pending")works butStatus("Pending")doesn't; the enum is the contract. - Iteration (
list(Status),for s in Status) yields canonical members in definition order — your "all valid statuses" list for free. auto()fills in values:1, 2, 3...forEnum/IntEnum, powers of two forFlag, lowercased names forStrEnum.
4.2 IntEnum, StrEnum, ReprEnum — the mixins#
Enum members are not int or str — Department.BILLING == 1 is False, and json.dumps rejects them. The mixed-in types fix that:
IntEnum— members areints:Priority.NORMAL < Priority.HIGHworks,Priority.HIGH + 1 == 4, JSON-serialisable as numbers. Since Python 3.11str()/format()useint's behaviour (drop-in replacement for integer constants).StrEnum(3.11+) — members arestrs:Status.OPEN == "open", usable anywhere a string is, JSON-serialises as"open", andauto()gives lowercased names.ReprEnum— the base that keepsstr()/format()of the mixed-in type forIntEnum/StrEnum/IntFlag; you subclass it only for custom mixed types.
The contrast in one line: str(Department.BILLING) → Department.BILLING (plain Enum shows ClassName.MEMBER) but str(Status.PENDING) → pending and str(Priority.HIGH) → 3. Pick StrEnum for string vocabularies, IntEnum for ordered numeric ones, plain Enum when the values are something else entirely (tuples, objects). One convention worth stating: our Priority numbers bigger = more urgent (URGENT is the maximum) — the same direction the priority ints used through Parts 1–3 and 01A.3's priority() take, and the one 01A.10's capstone reuses. Whichever direction you pick, write it down — mixing the two is how "priority 1" bugs are born.
4.3 Aliases and __members__#
Two names can share one value — the second becomes an alias:
from enum import Enum
class Colour(Enum):
RED = 1
CRIMSON = 1 # alias of RED
BLUE = 2
print("Colour.CRIMSON is Colour.RED ->", Colour.CRIMSON is Colour.RED)
print("list(Colour) ->", list(Colour)) # aliases skipped
print("__members__ keys ->", list(Colour.__members__))Colour.CRIMSON is Colour.RED -> True
list(Colour) -> [<Colour.RED: 1>, <Colour.BLUE: 2>]
__members__ keys -> ['RED', 'CRIMSON', 'BLUE']list() and iteration show only canonical members; __members__ (a dict-like mapping) includes aliases. Aliases are deliberate (renaming without breaking old code) — accidental ones are what @unique catches.
4.4 Flag and IntFlag — combinable values#
When values combine (permissions, capabilities, feature flags), Flag/IntFlag members support |, &, ^, ~ without losing membership:
from enum import IntFlag, auto
class Capability(IntFlag):
READ = auto() # 1
WRITE = auto() # 2
DELETE = auto() # 4
rw = Capability.READ | Capability.WRITE
print("rw ->", repr(rw), "| value ->", rw.value)
print("Capability.READ in rw ->", Capability.READ in rw)
print("Capability.DELETE in rw ->", Capability.DELETE in rw)
print("list(rw) ->", list(rw))
print("Capability(3) ->", repr(Capability(3)))
print("bool(Capability(0)) ->", bool(Capability(0)))rw -> <Capability.READ|WRITE: 3> | value -> 3
Capability.READ in rw -> True
Capability.DELETE in rw -> False
list(rw) -> [<Capability.READ: 1>, <Capability.WRITE: 2>]
Capability(3) -> <Capability.READ|WRITE: 3>
bool(Capability(0)) -> Falseauto() on a Flag assigns powers of two so combinations stay unambiguous. x in flag tests membership; combinations of named flags are valid members (Capability(3) above). Bits nobody named behave differently by type: IntFlag keeps them (Capability(8) is legal and prints as <Capability: 8>), while a plain Flag rejects them with ValueError by default (its FlagBoundary is STRICT). Use IntFlag when the value should behave as an int (bitmask storage, JSON as a number); Flag when you want pure enum semantics.
4.5 @unique and @verify — class-level checks#
Two decorators validate the enum at class creation:
from enum import CONTINUOUS, Enum, unique, verify
try:
@unique
class Mistake(Enum):
ONE = 1
TWO = 2
THREE = 3
FOUR = 3
except ValueError as e:
print("@unique ->", type(e).__name__, ":", e)
try:
@verify(CONTINUOUS)
class Level(Enum):
LOW = 1
MID = 3
except ValueError as e:
print("@verify ->", type(e).__name__, ":", str(e).splitlines()[0])@unique -> ValueError : duplicate values found in <enum 'Mistake'>: FOUR -> THREE
@verify -> ValueError : invalid enum 'Level': missing values 2@uniquerejects accidental aliases (FOUR = 3was probably a typo for4).@verify(...)(3.11+) appliesEnumCheckconstraints:UNIQUE(no two names share a value — aliases forbidden),CONTINUOUS(integer values with no gaps),NAMED_FLAGS(every Flag combination has a name). Failures raiseValueErrorwhen the class is defined — bugs caught at import, not at runtime.
4.6 JSON, comparison and the advanced hooks#
Two behaviours worth memorising:
json.dumps:StrEnum/IntEnumserialise natively ({"status": "open"},{"priority": 2}); plainEnumraisesTypeError: Object of type Department is not JSON serializable— use.valueor pick a mixed type.==across the boundary:Status.OPEN == "open"isTrueforStrEnum,Falsefor plainEnum— another reason to prefer the mixed types when the values are strings/numbers.
The advanced hooks (know they exist; rarely needed): _missing_(cls, value) — classmethod called when lookup fails, lets you accept aliases or parse strings; _generate_next_value_ — customise what auto() produces; @member/@nonmember (3.11+) — force or forbid membership for non-enum values in the class body; FlagBoundary — control whether out-of-range flag bits are kept, conformed or ejected; EnumDict (3.13) — the namespace class for exotic enums. The enum HOWTO covers them when you need them.
_missing_ in three lines — accept the member name as a fallback for the value lookup:
from enum import StrEnum
class FlexibleStatus(StrEnum):
OPEN = "open"
CLOSED = "closed"
@classmethod
def _missing_(cls, value):
# "OPEN" isn't a value — but it IS a member name; accept it.
if isinstance(value, str):
try:
return cls.__members__[value]
except KeyError:
pass
return None # None -> normal ValueError is raised
print(FlexibleStatus("OPEN")) # -> open
try:
FlexibleStatus("bogus")
except ValueError as e:
print("bogus ->", type(e).__name__, e)open
bogus -> ValueError 'bogus' is not a valid FlexibleStatusAnd for the rare case where a class body is impossible (building an enum inside a function, dynamically), there's a functional syntax: Status = Enum("Status", "OPEN CLOSED") or Status = Enum("Status", [("OPEN", "open"), ("CLOSED", "closed")]) — the class syntax is almost always clearer, but the functional form is what enum's own machinery uses under the hood.
4.7 Enums in AI code: statuses and finish reasons#
This is where enums earn their keep in the path:
- Ticket/record statuses (
Status.OPEN → IN_PROGRESS → RESOLVED) — the running example usesStrEnumso JSON round-trips are trivial. - Provider
finish_reasonvalues — every provider reports why generation stopped (stop,length,tool_calls,content_filter); 02.5 §4.5 maps them all, and modelling them as an enum in your client code is exactly what 03.11 does for its canonicalFinishReason. - Tool-call statuses, job states, moderation labels, routing decisions — anywhere a string vocabulary crosses a boundary, an enum is the difference between "works until someone typos" and "the type checker/imports catch it".
Part 5: Objects in real code#
Deep-dive
5.1 Identity, equality and copying#
Three comparisons people constantly confuse:
is— identity: "same object in memory?" (a is b⟺id(a) == id(b)). Use forNone(x is None), sentinel objects, and enum members (they're singletons —Status.OPEN is Status.OPENis alwaysTrue).==— equality: whatever__eq__says. For your classes, field-by-field.hash()— the dict/set key function; must agree with__eq__(1.4).
Copying objects has the same shallow/deep split as lists (01A.4):
import copy
from dataclasses import dataclass, field
@dataclass
class Ticket:
ticket_id: str
subject: str
tags: list[str] = field(default_factory=list)
t1 = Ticket("T-1", "Cannot log in", tags=["urgent"])
t2 = Ticket("T-1", "Cannot log in", tags=["urgent"])
print("t1 == t2 ->", t1 == t2)
print("t1 is t2 ->", t1 is t2)
# A mutable dataclass is UNHASHABLE: eq=True sets __hash__ = None.
t3 = Ticket("T-3", "x")
try:
hash(t3)
except TypeError as e:
print("hash(t3) ->", type(e).__name__, ":", e)
@dataclass(frozen=True)
class Money:
cents: int
currency: str = "USD"
m1 = Money(1999)
m2 = Money(1999)
print("frozen: m1 == m2 ->", m1 == m2, "| hash equal ->", hash(m1) == hash(m2))
print("set dedupe ->", len({m1, m2, Money(500)})) # equal+same hash -> one item
try:
m1.cents = 1
except Exception as e:
print("frozen assign ->", type(e).__name__)
# copy vs deepcopy on objects with mutable fields
t4 = copy.copy(t1) # shallow: shares the tags list
t5 = copy.deepcopy(t1) # deep: copies the list too
t4.tags.append("shallow-copy")
t5.tags.append("deep-copy")
print("t1.tags ->", t1.tags)
print("t4.tags ->", t4.tags) # same list object as t1!
print("t5.tags ->", t5.tags) # independent
# introspection: vars/dir/getattr
print("vars(t1) ->", vars(t1))
print("getattr ->", getattr(t1, "subject"), "|", getattr(t1, "missing", "n/a"))
print("hasattr ->", hasattr(t1, "priority"))
print("dir has 'tags' ->", "tags" in dir(t1))t1 == t2 -> True
t1 is t2 -> False
hash(t3) -> TypeError : unhashable type: 'Ticket'
frozen: m1 == m2 -> True | hash equal -> True
set dedupe -> 2
frozen assign -> FrozenInstanceError
t1.tags -> ['urgent', 'shallow-copy']
t4.tags -> ['urgent', 'shallow-copy']
t5.tags -> ['urgent', 'deep-copy']
vars(t1) -> {'ticket_id': 'T-1', 'subject': 'Cannot log in', 'tags': ['urgent', 'shallow-copy']}
getattr -> Cannot log in | n/a
hasattr -> False
dir has 'tags' -> Truecopy.copycopies the object but shares mutable attributes —t4.tags is t1.tags.copy.deepcopyrecursively copies everything reachable. Rule: shallow unless you specifically need isolation.- Introspection —
vars(obj)/obj.__dict__gives the attribute dict,dir(obj)lists all attribute names (own + inherited + class),getattr/setattr/hasattraccess by string name. This is how frameworks discover your fields: Pydantic reads__annotations__, dataclasses read them too, ORMs scan__dict__. When an SDK "magically" knows your model's fields, it's introspection.
5.2 Exceptions are classes too (preview)#
Every exception is an instance of a class deriving from Exception — which is why except ValueError catches ValueError and its subclasses, and why you can define your own hierarchy. 01A.8 owns the full treatment; here's the shape:
class TicketError(Exception):
"""Base for everything our triage code raises."""
class UnknownTicketError(TicketError):
def __init__(self, ticket_id: str):
super().__init__(f"no ticket with id {ticket_id!r}")
self.ticket_id = ticket_id
class InvalidTransitionError(TicketError):
pass
try:
raise UnknownTicketError("T-999")
except TicketError as e: # catches subclasses too
print("caught ->", type(e).__name__, ":", e)caught -> UnknownTicketError : no ticket with id 'T-999'Custom exceptions let callers except TicketError for "anything triage-related" while still catching UnknownTicketError specifically — the same hierarchy pattern provider SDKs use (APIError → RateLimitError, 03.8) and 03.11 builds its canonical error tree on.
5.3 Dependency injection is "pass the thing in" (preview)#
There's no framework magic here — dependency injection is just constructing objects with their collaborators passed in:
# continues this part's file — Ticket is the dataclass from 5.1
def triage(tickets: list[Ticket], classifier) -> dict[str, str]:
return {t.ticket_id: classifier.classify(t) for t in tickets}
class KeywordClassifier:
def __init__(self, keywords):
self.keywords = keywords
def classify(self, ticket: Ticket) -> str:
text = ticket.subject.lower()
for label, words in self.keywords.items():
if any(w in text for w in words):
return label
return "general"
class LengthClassifier:
def classify(self, ticket: Ticket) -> str:
return "quick" if len(ticket.subject) < 30 else "needs-review"
tickets = [Ticket("T-1", "Charged twice on my invoice"),
Ticket("T-2", "where is my order"),
Ticket("T-3", "a much longer subject line about a billing dispute")]
kw = KeywordClassifier({"billing": ("invoice", "charge", "billing"),
"orders": ("order",)})
lc = LengthClassifier()
print("keyword ->", triage(tickets, kw))
print("length ->", triage(tickets, lc))keyword -> {'T-1': 'billing', 'T-2': 'orders', 'T-3': 'billing'}
length -> {'T-1': 'quick', 'T-2': 'quick', 'T-3': 'needs-review'}triage() doesn't know or care which classifier it gets — swap implementations by passing a different object, and tests inject a fake with no constructor changes. This is the seam every later lesson exploits: FastAPI's Depends (01B.7), pytest fixtures (01B.8), and the ChatModel Protocol fakes in 03.10 are all this same idea at larger scale.
5.4 When not to write a class#
Classes earn their keep when data and behaviour belong together and the thing has identity or invariants. They are overhead when:
- The "object" is just a bag of values with no behaviour — a dict or a
NamedTuple/frozen dataclass is simpler. (A frozen dataclass is allowed here — it's a record, not really "a class" in the behavioural sense.) - One function would do —
slugify(text)doesn't need aSlugifierclass unless you must swap implementations (then a Protocol + two tiny classes is worth it). - The class would only hold config — a dict or a
pydantic-settingsBaseSettings(01B.2) beats a class full ofself.x = config["x"]. - You're modelling a language construct, not a domain thing — don't wrap
list/dict/strin classes for purity's sake; wrap them when you add domain meaning (TicketBoard,Report).
The Pythonic bias: functions and modules first, classes when the domain demands them. "Everything is an object" doesn't mean "make everything a class".
5.5 The patterns that matter: strategy, adapter, registry#
Three small patterns recur throughout the AI path — learn their names now, they're one idea each:
- Strategy — a family of interchangeable algorithms behind one interface. Your
ClassifierProtocol +KeywordClassifier/LengthClassifieris a strategy pattern:triage(tickets, classifier)picks the strategy by argument. - Adapter — translates one interface to another. 03.11's provider adapters convert canonical
Request/Responsetypes to each provider's wire format; yourfrom_dictclassmethod is a micro-adapter (dict→Ticket). - Registry — a dict mapping names to implementations, looked up at runtime:
# registry_demo.py
class KeywordClassifier:
def __init__(self, keywords):
self.keywords = keywords
def classify(self, ticket):
text = ticket.subject.lower()
for label, words in self.keywords.items():
if any(w in text for w in words):
return label
return "general"
class LengthClassifier:
def classify(self, ticket):
return "quick" if len(ticket.subject) < 30 else "needs-review"
CLASSIFIERS = {
"keyword": KeywordClassifier({"billing": ("invoice", "refund")}),
"length": LengthClassifier(),
}
def classify_with(name: str, ticket) -> str:
try:
return CLASSIFIERS[name].classify(ticket)
except KeyError:
raise ValueError(f"unknown classifier {name!r}; "
f"have {sorted(CLASSIFIERS)}") from None
class T:
def __init__(self, subject): self.subject = subject
t = T("Refund for my invoice")
for name in ["keyword", "length"]:
print(f"{name}: {classify_with(name, t)}")
try:
classify_with("magic", t)
except ValueError as e:
print("bad name ->", e)keyword: billing
length: quick
bad name -> unknown classifier 'magic'; have ['keyword', 'length']This scales directly: 08A.6's ToolRegistry maps tool names to callables for the agent loop, and 03.11's capability registry maps model aliases to provider chains — same dict, bigger stakes.
5.6 Design checklist#
Before writing a class, ask:
- Does it bundle data and the behaviour that belongs to it? (yes → class/dataclass)
- Is it a fixed vocabulary? (→
enum) - Is it a record crossing a boundary? (→ dataclass internally, Pydantic at the edge)
- Do I need to swap implementations? (→ Protocol/ABC + composition, not inheritance)
- Is it immutable-by-nature? (→
frozen=True— free hash, free safety) - Am I reaching for MI to reuse code? (→ probably composition or a mixin instead)
Part 6: The ticket-triage toolkit, assembled#
Deep-dive
Everything in this lesson converges here — the same toolkit 01A.9 will persist to disk. Tickets are dataclasses, vocabularies are enums, the classifier is a Protocol, storage is a small class:
# triage_toolkit.py (part 1 of 3): vocabularies, data, exceptions
import json
from collections import Counter
from dataclasses import dataclass, field
from enum import IntEnum, StrEnum
from typing import Protocol, runtime_checkable
class Priority(IntEnum):
LOW = 1
NORMAL = 2
HIGH = 3
URGENT = 4
class Status(StrEnum):
OPEN = "open"
IN_PROGRESS = "in_progress"
RESOLVED = "resolved"
CLOSED = "closed"
class TicketError(Exception):
"""Base for everything the toolkit raises."""
class UnknownTicketError(TicketError):
def __init__(self, ticket_id: str):
super().__init__(f"no ticket with id {ticket_id!r}")
self.ticket_id = ticket_id
@dataclass(frozen=True)
class Customer:
customer_id: str
name: str
email: str
plan: str = "free"
@dataclass
class Ticket:
ticket_id: str
customer: Customer
subject: str
priority: Priority = Priority.NORMAL
status: Status = Status.OPEN
tags: list[str] = field(default_factory=list)
notes: list[str] = field(default_factory=list)
def escalate(self) -> None:
"""Move one step more urgent and mark as being handled."""
if self.priority < Priority.URGENT:
self.priority = Priority(self.priority + 1)
self.status = Status.IN_PROGRESS
def summary_line(self) -> str:
return (f"{self.ticket_id} [{self.priority.name}] {self.status.value}: "
f"{self.subject} ({self.customer.name})")# triage_toolkit.py (part 2 of 3): the classifier seam
@runtime_checkable
class Classifier(Protocol):
"""Anything with a classify(ticket) -> str method fits."""
def classify(self, ticket: Ticket) -> str: ...
class KeywordClassifier:
def __init__(self, keywords: dict[str, tuple[str, ...]]):
self.keywords = keywords
def classify(self, ticket: Ticket) -> str:
text = ticket.subject.lower()
for label, words in self.keywords.items():
if any(w in text for w in words):
return label
return "general"
class LengthClassifier:
"""Routes by how much writing the ticket needs."""
def classify(self, ticket: Ticket) -> str:
return "quick" if len(ticket.subject) < 30 else "needs-review"# triage_toolkit.py (part 3 of 3): the store, data and main()
class TicketStore:
def __init__(self):
self._tickets: dict[str, Ticket] = {}
def add(self, ticket: Ticket) -> None:
if ticket.ticket_id in self._tickets:
raise TicketError(f"duplicate ticket id {ticket.ticket_id!r}")
self._tickets[ticket.ticket_id] = ticket
def get(self, ticket_id: str) -> Ticket:
try:
return self._tickets[ticket_id]
except KeyError:
raise UnknownTicketError(ticket_id) from None
def all(self) -> list[Ticket]:
return list(self._tickets.values())
def by_status(self, status: Status) -> list[Ticket]:
return [t for t in self._tickets.values() if t.status == status]
def summary(self) -> dict[str, int]:
return dict(Counter(t.status.value for t in self._tickets.values()))
def sample_tickets() -> list[Ticket]:
priya = Customer("C-100", "Priya Nair", "priya@example.com", plan="pro")
omar = Customer("C-101", "Omar Haddad", "omar@example.com")
return [
Ticket("T-1001", priya, "Charged twice on my invoice", Priority.HIGH,
tags=["double-charge"]),
Ticket("T-1002", omar, "Cannot log in after password reset",
Priority.URGENT, tags=["cant-login", "urgent"]),
Ticket("T-1003", priya, "How do I export my data?", Priority.LOW,
status=Status.RESOLVED, tags=["how-to"]),
Ticket("T-1004", omar, "A much longer subject line about a delayed refund",
Priority.NORMAL),
]
def main() -> None:
store = TicketStore()
classifier: Classifier = KeywordClassifier({
"billing": ("invoice", "charge", "refund", "billing"),
"login": ("log in", "login", "password"),
"account": ("export", "delete", "data"),
})
for ticket in sample_tickets():
label = classifier.classify(ticket)
ticket.tags.append(label)
store.add(ticket)
print("== tickets ==")
for ticket in store.all():
print(" ", ticket.summary_line(), "| tags:", ticket.tags)
print("== by status ==")
for status in Status:
print(f" {status.value}: {len(store.by_status(status))}")
print("== summary ==", store.summary())
urgent = store.get("T-1002")
print("== escalate T-1002 ==")
urgent.escalate()
print(" ", urgent.summary_line())
print("== serialise one ticket to JSON ==")
print(" ", json.dumps({
"id": urgent.ticket_id,
"priority": int(urgent.priority), # IntEnum -> plain int for JSON
"status": urgent.status.value, # StrEnum .value -> plain str
"customer": urgent.customer.customer_id,
}))
if __name__ == "__main__":
main()Save all three parts as one file triage_toolkit.py and run python3 triage_toolkit.py:
== tickets ==
T-1001 [HIGH] open: Charged twice on my invoice (Priya Nair) | tags: ['double-charge', 'billing']
T-1002 [URGENT] open: Cannot log in after password reset (Omar Haddad) | tags: ['cant-login', 'urgent', 'login']
T-1003 [LOW] resolved: How do I export my data? (Priya Nair) | tags: ['how-to', 'account']
T-1004 [NORMAL] open: A much longer subject line about a delayed refund (Omar Haddad) | tags: ['billing']
== by status ==
open: 3
in_progress: 0
resolved: 1
closed: 0
== summary == {'open': 3, 'resolved': 1}
== escalate T-1002 ==
T-1002 [URGENT] in_progress: Cannot log in after password reset (Omar Haddad)
== serialise one ticket to JSON ==
{"id": "T-1002", "priority": 4, "status": "in_progress", "customer": "C-101"}Every idea from this lesson is doing work: Priority/Status are enums guarding the vocabulary; Customer is a frozen value object (hashable, safe to share); Ticket is a dataclass with default_factory lists and real methods; Classifier is a Protocol so LengthClassifier could be swapped in with zero changes; TicketStore encapsulates the dict and raises domain exceptions; escalate() shows behaviour living on the object. 01A.9 adds CSV/JSON persistence to exactly this shape.
Common misconceptions#
| Misconception | Reality |
|---|---|
"A mutable dataclass field default like tags: list = [] works like a function default." |
It's rejected — ValueError: mutable default ... use default_factory. The shared-list trap is real, so the decorator guards it. Use field(default_factory=list). |
"__eq__ means the object is also hashable." |
Defining __eq__ sets __hash__ = None — the object becomes unhashable on purpose. Frozen dataclasses get a generated __hash__; mutable ones don't. |
"a == b means they're the same object." |
== calls __eq__ (field comparison); is is identity. Two Ticket("T-1", ...) instances are equal but not identical — and enum members are identical and equal. |
"Private means __x hides the attribute." |
Name mangling only renames it to _ClassName__x — still reachable, still Python. _x is a convention request; real protection is not storing secrets client-side. |
| "Inheritance is how you reuse code." | Inheritance is for "is-a" hierarchies; "has-a"/"uses-a" is composition. Deep class trees are where Python's MI sharp edges live — prefer holding collaborators and passing them in. |
"A class needs __init__ to be useful." |
Dataclasses generate it; a class with only methods and class attributes is legal. Write __init__ only when instances need per-object state set up. |
"self is optional boilerplate." |
It's the instance — forget it and x = x creates a local while self.x never gets set; you get AttributeError at first use, not at definition. |
| "Enums are just strings with extra steps." | StrEnum members are strings (that's the point — JSON and == work), but Status.OPEN is a singleton with .name/.value, iteration, lookup-by-value and typo-proofing that a bare "open" can't give you. |
| "Protocols require inheriting from them." | No — that's the whole point of structural typing. Any class with classify(self, ticket) -> str satisfies the Protocol without declaring it. @runtime_checkable is only needed for isinstance. |
"super() means 'call the parent class'." |
It means "the next class in this instance's MRO" — which is why cooperative mixins work in diamonds. |
"copy.copy gives me an independent object." |
Shallow: mutable attributes (lists, dicts) are shared with the original. Use copy.deepcopy when you need isolation. |
| "More classes = better design." | Overhead without payoff. A dict, a tuple-returning function, or a module of functions is often the right answer — classes earn their keep when data+behaviour+invariants belong together. |
Reading the real errors#
The four errors you'll actually hit, verbatim (paths trimmed — wordings are the 3.13+ forms; on 3.11–3.12 the dataclass message drops the trailing 'a', as noted in 3.2):
# forgetting self.x = ... inside __init__
AttributeError: 'Broken' object has no attribute 'x'
# a non-default dataclass field after a defaulted one
TypeError: non-default argument 'b' follows default argument 'a'
# calling an instance method on the class, forgetting the instance
TypeError: Greeter.hello() missing 1 required positional argument: 'self'
# looking up an unknown enum value
ValueError: 'pending' is not a valid StatusEach names the fix: assign on self, reorder fields or give defaults, instantiate first, use a real member.
Key takeaways#
- Classes bundle data and behaviour.
selfis the instance;__init__fills it; attributes spring into existence by assignment. Class-body attributes are shared — mutable ones are almost always a bug. - Dunders make objects Pythonic.
__repr__/__str__for printing,__eq__+__hash__(they must agree!) for comparison,__lt__+@total_orderingfor sorting,__len__/__iter__/__getitem__/__contains__for collection behaviour,__call__for callable instances,__enter__/__exit__forwith. @propertygives computed attributes and validated setters;@classmethodbuilds alternative constructors (from_dict);@staticmethodis a namespaced function._x/__xare conventions, not enforcement;__slots__trades flexibility for memory/speed.- Prefer composition over inheritance. Inheritance for "is-a" (rare), composition for "uses-a" (everywhere).
super()walks the MRO — learn to readClass.__mro__. ABCs enforce interfaces;typing.Protocolchecks them structurally without inheritance. @dataclasswrites your boilerplate. Declare annotated fields; get__init__/__repr__/__eq__free.field(default_factory=...)for mutable defaults,frozen=Truefor value objects (and free hashing),order=True/kw_only=True/slots=Truefor the rest,__post_init__for validation,asdict/replace/fieldsfor the toolkit. Mutable dataclasses are deliberately unhashable.- Enums make vocabularies safe.
StrEnumfor string values (JSON-free,==-with-strings),IntEnumfor ordered numbers,Flag/IntFlagfor combinations,auto()for values,@unique/@verifyfor class-creation checks. Bare strings are a typo waiting to happen. - Real code is wiring.
isvs==vshash,copyvsdeepcopy,vars/dir/getattrintrospection, exceptions-as-classes, and "pass the thing in" dependency injection — plus strategy/adapter/registry patterns you'll recognise from 03.11 and 08A.6. - When in doubt: dataclass inside, Pydantic at the boundary, enum for vocabularies, Protocol for swappable collaborators.
Where you'll use this in the AI path#
| Forward link | What you'll find there |
|---|---|
| 01B.6 — Pydantic | The validation layer this lesson previews: BaseModel is a dataclass with runtime-checked fields, JSON Schema export and coercion — the boundary counterpart to plain dataclasses |
| 03.1 §8.3 — SDK objects | Every provider SDK response is a Pydantic model — the same "data with a shape" idea, validated |
| 03.4 — Structured output | Pydantic models are the schema language for forcing models to return typed JSON — the payoff of understanding dataclasses |
| 03.11 — Provider-agnostic client | Canonical dataclasses + Protocol interfaces + per-provider adapters + a capability registry — Parts 4–7 are this lesson at production scale |
| 03.10 — Debugging and testing | ScriptedModel/ScriptedBackend fakes injected through Protocol seams — dependency injection in action |
| 08A.6 — Designing tools | ToolRegistry: the registry pattern from 5.5 running the agent loop |
| 02.5 §4.5 — Finish reasons | Per-provider stop reasons that 03.11 unifies into one enum |
| 06.1 — Embedding models | The Embedder Protocol — structural typing deciding what "an embedder" means |
| 01A.7 — Modules and the stdlib | dataclasses, enum, abc, typing, functools, copy all live there — the tour picks up where this lesson stops |
| 01A.8 — Errors, debugging, logging | Exception hierarchies and context managers in full |
| 01A.9 — Files, JSON and CSV | Persisting exactly the Ticket/Customer dataclasses from Part 6 |
| 01A.10 — Type hints | Protocol, TypedDict, annotations — the static side of everything here |
Terms introduced in this lesson#
| Term | What it means here |
|---|---|
| Class | A blueprint defining attributes and methods; instances are objects created from it |
| Instance | A single object created from a class (t = Ticket(...)) |
self |
The first parameter of an instance method — the object the method was called on |
__init__ |
The initialiser Python calls on Class(...); fills in instance attributes |
| Dunder method | A __x__ method Python calls implicitly for syntax like print(), ==, len() |
| Instance attribute | self.x = ... — data belonging to one object |
| Class attribute | A name defined in the class body — one value shared by all instances |
__repr__ / __str__ |
Developer-facing vs user-facing string conversions |
__eq__ / __hash__ |
Equality and hashability — must agree; defining __eq__ alone makes the object unhashable |
__lt__ / total_ordering |
Ordering comparison plus the decorator that derives <=, >, >= |
| Collection dunders | __len__, __iter__, __getitem__, __contains__ — making an object quack like a built-in |
__call__ |
Makes an instance callable like a function |
@property |
Turns a method into attribute access; getter/setter pairs enable validation |
@classmethod / @staticmethod |
Methods bound to the class (cls) or to nothing — factories vs namespaced functions |
| Name mangling | __x stored as _Class__x — anti-collision, not privacy |
__slots__ |
Replaces __dict__ with fixed attribute slots — smaller, faster, no dynamic attrs |
| Inheritance | class B(A) — B is an A; reuse via super() and overriding |
| MRO (method resolution order) | The C3 linearisation deciding which method wins; super() walks it |
| Composition | Holding collaborators as attributes instead of inheriting them |
| Abstract base class | abc.ABC + @abstractmethod — an interface that can't be instantiated |
typing.Protocol |
Structural interface — satisfied by shape, not inheritance; @runtime_checkable enables isinstance |
| Structural typing / duck typing | "If it quacks like a classifier, it is one" — checked by Protocols |
| Mixin | A small capability class combined via multiple inheritance |
dataclass |
@dataclass generates __init__/__repr__/__eq__ from annotated fields |
field(default_factory=...) |
Per-instance default for mutable/expensive fields |
frozen dataclass |
Immutable instance; gets __hash__ for free — the value-object pattern |
kw_only / slots / order |
Dataclass flags for keyword-only init, __slots__, and ordering dunders |
__post_init__ |
Hook run at the end of generated __init__ — for validation |
asdict / astuple / replace / fields |
Dataclass helpers for dict/tuple conversion, copying-with-changes, introspection |
| Value object | An immutable object defined by its fields (Money, Point) — equal ⟺ interchangeable |
Enum / member |
A fixed vocabulary of named values; members have .name and .value |
IntEnum / StrEnum |
Enums whose members are ints/strings — JSON-friendly, comparable to primitives |
auto() |
Generates enum values automatically (ints, powers of two for Flags, names for StrEnum) |
Flag / IntFlag |
Enums whose members combine bitwise (READ | WRITE) |
| Alias | Two member names sharing one value; canonical member wins iteration |
@unique / @verify |
Decorators validating enum definitions at class-creation time |
| Introspection | Examining objects at runtime: vars, dir, getattr, __annotations__ |
copy / deepcopy |
Shallow (shared mutables) vs deep (fully independent) object copies |
| Dependency injection | Passing collaborators into constructors/functions instead of hard-coding them |
| Strategy / adapter / registry | Interchangeable algorithms / interface translation / name→implementation lookup |
Exercises#
-
Frozen value object. Write
@dataclass(frozen=True)Money(cents: int, currency: str = "USD")with a__post_init__that uppercasescurrency(hint:object.__setattr__works on frozen instances). PutMoney(1999),Money(1999, "usd")andMoney(500)in aset, sort bycents, and print — why did the set end up with two items, not three? -
The mutable-default fix. This dataclass is broken — explain why and fix it:
python @dataclass class Ticket: ticket_id: str tags: list[str] = []Then create two tickets, append a tag to one, and show the other is unaffected.
-
Ordering. Make
@dataclass(order=True)Rank(priority: int, ticket_id: str, subject: str = "")where biggerprioritymeans more urgent (1=LOW … 4=URGENT), and usesorted(ranks, reverse=True)on a scrambled queue so URGENT comes first. Why mustprioritybe declared beforeticket_id— and what doesreverse=Truedo to theticket_idtiebreak? -
Validated property. Give
Customeranemailproperty with a setter that rejects values without"@"and a.after it, plus a computeddisplay_nameproperty. Try assigning a bad email and show theValueError. -
Quack like a list. Implement
__len__,__iter__,__getitem__,__contains__,__repr__onPlaylistwrappingself._tracks. Showlen(), indexing, a slice,in, andforall working. -
total_ordering. Implement__eq__and__lt__forVersion(major, minor, patch)comparing tuples, decorate with@total_ordering, andsorted()[1.10.0, 1.9.9, 2.0.0, 1.9.10]— plus<=and>checks. -
MRO prediction. Given
SpecialTicket(TimedTicket, AuditedTicket)where both parents overridedescribe()and callsuper(), predict__mro__and thedescribe()output before running it. Verify. -
ABC. Define
Notifier(ABC)with abstractsend(message) -> str, implementEmailNotifierandSmsNotifier, and show thatNotifier()raisesTypeErrorwhile the subclasses work. -
Protocol check. Define
@runtime_checkableRenderable(Protocol)withrender() -> str. Checkisinstancefor a class that hasrender, one that doesn't, and42. -
Enum workflow. Write
TicketState(StrEnum)(OPEN,IN_PROGRESS,RESOLVED,CLOSED), anext_state()helper usinglist(TicketState).index(), walk a ticket toCLOSED, and look one up by value and by name. -
Flag permissions. Write
Perm(IntFlag)withREAD/WRITE/DELETE, combineREAD | WRITE, checkPerm.DELETE in role, and print the combined.value. -
Copy semantics. For a
Ticketdataclass with atagslist, showcopy.copyshares the list whilecopy.deepcopydoesn't — mutate each copy's tags and print all three. -
Registry dispatch. Build
CLASSIFIERS = {"keyword": ..., "length": ...}andclassify_with(name, ticket)that raises a helpfulValueErroron an unknown name. Dispatch both classifiers on one ticket. -
Conceptual. Your script has
def summarise_ticket(ticket_dict) -> dictthat just reshapes a dict. A colleague says "make it a class". Argue both sides using 5.4 — when would you actually write the class? -
Guarded transition. Add
close()to aTicketclass that raisesInvalidTransitionError(TicketError)unlessstatus == "resolved"; catch it via the base class, then resolve and close successfully.
Answers
1. Frozen value object
object.__setattr__ is needed because frozen=True blocks normal assignment, even inside __post_init__.
from dataclasses import dataclass
@dataclass(frozen=True)
class Money:
cents: int
currency: str = "USD"
def __post_init__(self) -> None:
# frozen blocks normal assignment, so bypass it once, during construction
object.__setattr__(self, "currency", self.currency.upper())
wallet = {Money(1999), Money(1999, "usd"), Money(500)}
print(len(wallet), "items")
print(sorted(wallet, key=lambda m: m.cents))2 items
[Money(cents=500, currency='USD'), Money(cents=1999, currency='USD')]The set has two items, not three: Money(1999) and Money(1999, "usd") become equal once __post_init__ has uppercased the currency, and frozen dataclasses generate __eq__ and __hash__ from the same fields, so the set treats them as one value.
2. The mutable-default fix
tags: list[str] = [] is a shared mutable default, so Python rejects it for dataclasses (ValueError: mutable default ... use default_factory). Fix: field(default_factory=list), which builds a fresh list per instance.
from dataclasses import dataclass, field
@dataclass
class Ticket:
ticket_id: str
tags: list[str] = field(default_factory=list)
a = Ticket("T-1")
b = Ticket("T-2")
a.tags.append("billing")
print("a.tags ->", a.tags, "| b.tags ->", b.tags)a.tags -> ['billing'] | b.tags -> []3. Ordering
order=True compares the fields as a tuple in declaration order, so priority must come first or ticket_id would dominate the sort. reverse=True reverses the whole comparison, tiebreak included: equal priorities come out by ticket_id descending (T-9 before T-2).
from dataclasses import dataclass
@dataclass(order=True)
class Rank:
priority: int # compared first, so it must be declared first
ticket_id: str
subject: str = ""
queue = [
Rank(2, "T-5", "Export"),
Rank(4, "T-2", "Crash on save"),
Rank(1, "T-3", "Invoice question"),
Rank(4, "T-9", "Login outage"),
Rank(3, "T-7", "Password reset"),
]
for r in sorted(queue, reverse=True):
print(" ", r) Rank(priority=4, ticket_id='T-9', subject='Login outage')
Rank(priority=4, ticket_id='T-2', subject='Crash on save')
Rank(priority=3, ticket_id='T-7', subject='Password reset')
Rank(priority=2, ticket_id='T-5', subject='Export')
Rank(priority=1, ticket_id='T-3', subject='Invoice question')If you need URGENT-first and ascending-id tiebreaks, sort with key=lambda r: (-r.priority, r.ticket_id) instead — the negated-rank trick from 01A.4.
4. Validated property
The stricter check is "@" not in value or "." not in value.split("@")[-1]; the setter runs on every assignment, including the one inside __init__.
class Customer:
def __init__(self, name: str, email: str) -> None:
self.name = name
self.email = email # goes through the setter
@property
def email(self) -> str:
return self._email
@email.setter
def email(self, value: str) -> None:
if "@" not in value or "." not in value.split("@")[-1]:
raise ValueError(f"not an email address: {value!r}")
self._email = value
@property
def display_name(self) -> str:
return f"{self.name} <{self._email}>"
c = Customer("Priya", "priya@example.com")
print(c.display_name)
try:
c.email = "priya-at-example"
except ValueError as e:
print("rejected ->", e)Priya <priya@example.com>
rejected -> not an email address: 'priya-at-example'5. Quack like a list
Same four dunders as TicketBoard in 1.5; slicing works because __getitem__ just forwards the index (a slice object) to the inner list.
class Playlist:
def __init__(self, tracks=()):
self._tracks = list(tracks)
def __len__(self) -> int:
return len(self._tracks)
def __iter__(self):
return iter(self._tracks)
def __getitem__(self, index):
return self._tracks[index]
def __contains__(self, track) -> bool:
return track in self._tracks
def __repr__(self) -> str:
return f"Playlist({self._tracks!r})"
pl = Playlist(["song-a", "song-b", "song-c"])
print("len ->", len(pl), "| pl[0] ->", pl[0], "| pl[-1] ->", pl[-1])
print("slice ->", pl[1:], "| 'song-b' in pl ->", "song-b" in pl)
print("for t in pl ->", [t for t in pl])
print(pl)len -> 3 | pl[0] -> song-a | pl[-1] -> song-c
slice -> ['song-b', 'song-c'] | 'song-b' in pl -> True
for t in pl -> ['song-a', 'song-b', 'song-c']
Playlist(['song-a', 'song-b', 'song-c'])6. total_ordering
__eq__ and __lt__ compare (major, minor, patch) tuples and return NotImplemented for non-Version operands; @total_ordering supplies <=, > and >=. Note 1.10.0 sorts after 1.9.10 because the parts are integers, not text.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major: int, minor: int, patch: int) -> None:
self.parts = (major, minor, patch)
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
def __repr__(self) -> str:
return "{}.{}.{}".format(*self.parts)
versions = [Version(1, 10, 0), Version(1, 9, 9), Version(2, 0, 0), Version(1, 9, 10)]
print("sorted ->", sorted(versions))
print("1.9.9 <= 1.9.10 ->", Version(1, 9, 9) <= Version(1, 9, 10))
print("2.0.0 > 1.10.0 ->", Version(2, 0, 0) > Version(1, 10, 0))sorted -> [1.9.9, 1.9.10, 1.10.0, 2.0.0]
1.9.9 <= 1.9.10 -> True
2.0.0 > 1.10.0 -> True7. MRO prediction
TimedTicket's super() continues to AuditedTicket, not straight to Ticket, because super() walks the instance's MRO, so every layer contributes.
class Ticket:
def describe(self) -> str:
return "ticket"
class TimedTicket(Ticket):
def describe(self) -> str:
return "timed+" + super().describe()
class AuditedTicket(Ticket):
def describe(self) -> str:
return "audited+" + super().describe()
class SpecialTicket(TimedTicket, AuditedTicket):
pass
print([c.__name__ for c in SpecialTicket.__mro__])
print(SpecialTicket().describe())['SpecialTicket', 'TimedTicket', 'AuditedTicket', 'Ticket', 'object']
timed+audited+ticket8. ABC
The abstract method makes Notifier() impossible to instantiate; the subclasses work because they implement send. (On Python 3.11 the wording is Can't instantiate abstract class Notifier with abstract method send.)
from abc import ABC, abstractmethod
class Notifier(ABC):
@abstractmethod
def send(self, message: str) -> str: ...
class EmailNotifier(Notifier):
def send(self, message: str) -> str:
return f"email sent: {message!r}"
class SmsNotifier(Notifier):
def send(self, message: str) -> str:
return f"sms sent: {message!r}"
try:
Notifier()
except TypeError as e:
print("Notifier() ->", type(e).__name__, ":", e)
for n in (EmailNotifier(), SmsNotifier()):
print(n.send("your ticket was resolved"))Notifier() -> TypeError : Can't instantiate abstract class Notifier without an implementation for abstract method 'send'
email sent: 'your ticket was resolved'
sms sent: 'your ticket was resolved'9. Protocol check
The runtime check only looks for a render attribute; it says nothing about signatures.
from typing import Protocol, runtime_checkable
@runtime_checkable
class Renderable(Protocol):
def render(self) -> str: ...
class Ticket:
def render(self) -> str:
return "<ticket>"
class Customer:
pass
for obj in (Ticket(), Customer(), 42):
print(type(obj).__name__, "is Renderable ->", isinstance(obj, Renderable))Ticket is Renderable -> True
Customer is Renderable -> False
int is Renderable -> False10. Enum workflow
list(TicketState) is the definition order, so index() + 1 is the next state; min(...) keeps CLOSED as the end.
from enum import StrEnum
class TicketState(StrEnum):
OPEN = "open"
IN_PROGRESS = "in_progress"
RESOLVED = "resolved"
CLOSED = "closed"
def next_state(state: TicketState) -> TicketState:
order = list(TicketState) # definition order
return order[min(order.index(state) + 1, len(order) - 1)]
state = TicketState.OPEN
while state is not TicketState.CLOSED:
print(state.value, "->", next_state(state).value)
state = next_state(state)
print("lookup by value:", TicketState("resolved").value)
print("lookup by name :", TicketState["IN_PROGRESS"].value)open -> in_progress
in_progress -> resolved
resolved -> closed
lookup by value: resolved
lookup by name : in_progress11. Flag permissions
auto() on a flag gives powers of two (1, 2, 4), so READ | WRITE is 3 and every combination is unambiguous.
from enum import IntFlag, auto
class Perm(IntFlag):
READ = auto()
WRITE = auto()
DELETE = auto()
role = Perm.READ | Perm.WRITE
print("role ->", repr(role), "| value ->", role.value)
print("can read ->", Perm.READ in role)
print("can delete ->", Perm.DELETE in role)
admin = Perm.READ | Perm.WRITE | Perm.DELETE
print("admin has all ->", all(p in admin for p in Perm))
print("Perm(7) ->", repr(Perm(7)))role -> <Perm.READ|WRITE: 3> | value -> 3
can read -> True
can delete -> False
admin has all -> True
Perm(7) -> <Perm.READ|WRITE|DELETE: 7>12. Copy semantics
copy.copy copies the dataclass but shares the tags list; deepcopy copies the list too.
import copy
from dataclasses import dataclass, field
@dataclass
class Ticket:
ticket_id: str
tags: list[str] = field(default_factory=list)
t = Ticket("T-1", ["billing"])
shallow = copy.copy(t)
deep = copy.deepcopy(t)
shallow.tags.append("shallow-only")
deep.tags.append("deep-only")
print("t.tags ->", t.tags)
print("shallow.tags ->", shallow.tags, "(shared with t!)")
print("deep.tags ->", deep.tags)t.tags -> ['billing', 'shallow-only']
shallow.tags -> ['billing', 'shallow-only'] (shared with t!)
deep.tags -> ['billing', 'deep-only']13. Registry dispatch
The complete CLASSIFIERS / classify_with code and its output are in 5.5: keyword: billing, length: quick, then bad name -> unknown classifier 'magic'; have ['keyword', 'length']. Writing it yourself first, then comparing, is the exercise.
14. Conceptual
For the class: encapsulation of the reshape rules, swappable implementations, isinstance checks. Against: it is a pure function over a dict — no state, no invariants, one caller — so a class adds ceremony with no payoff (5.4). Write the class when the "summary" gains behaviour (validation, several output formats, caching) or when you need to inject different summariser strategies.
15. Guarded transition
except TicketError catches InvalidTransitionError because it is a subclass; once the ticket is resolved, close() succeeds.
class TicketError(Exception):
"""Base for everything the toolkit raises."""
class InvalidTransitionError(TicketError):
pass
class Ticket:
def __init__(self, ticket_id: str) -> None:
self.ticket_id = ticket_id
self.status = "open"
def resolve(self) -> None:
self.status = "resolved"
def close(self) -> None:
if self.status != "resolved":
raise InvalidTransitionError(
f"{self.ticket_id} is {self.status!r}, not 'resolved'")
self.status = "closed"
t = Ticket("T-1")
try:
t.close()
except TicketError as e: # the base class catches the subclass
print("caught ->", type(e).__name__, ":", e)
t.resolve()
t.close()
print("after resolve ->", t.status)caught -> InvalidTransitionError : T-1 is 'open', not 'resolved'
after resolve -> closedCheck yourself#
- What's the difference between a class attribute and an instance attribute, and why is
tags = []in a class body a bug?Class attributes live on the class — one shared value for all instances; instance attributes live on each object. A mutable class attribute (tags = []) is shared, so appends leak across instances — initialise per-instance in__init__(orfield(default_factory=list)). - Why does defining
__eq__make your object unhashable — and how doesfrozen=Truefix that?Python sets__hash__ = Nonewhen you define__eq__, enforcing "equal objects must hash equal".frozen=Truemakes instances immutable so the generated hash can't go stale — you get__hash__back. print(t)showsT-1: Cannot log inbutprint([t])showsTicket(ticket_id='T-1', ...). Which dunders are involved?print(t)/str()/f"{t}"use__str__; containers display elements with__repr__. That's why the list shows the verbose form.- A subclass defines
__init__but never callssuper().__init__(). What breaks, and when?The parent's attributes are never set — the first inherited method touchingself.ticket_idraisesAttributeErrorat call time, not at construction. - When would you choose
typing.Protocoloverabc.ABCfor a classifier interface — and what does@runtime_checkableadd?Protocol when you want structural checks without forcing inheritance (fakes, third-party classes); ABC when you want enforced implementation + shared concrete methods +isinstanceby nominal type.@runtime_checkableenablesisinstance/issubclassagainst the Protocol at runtime. - Your dataclass has
items: list = []. What happens at import, and what's the fix?ValueError: mutable default <class 'list'> for field items is not allowed: use default_factory— at class decoration. Fix:field(default_factory=list). Money(1999) == Money(1999)isTruebut they're different objects. Which comparison operators distinguish them, and which one would you use in aset?==(field equality via__eq__) vsis(identity). In aset, equal+same-hash dedupes — frozen dataclass instances collapse to one member.Status.OPEN == "open"isTrueforStrEnumbutDepartment.BILLING == 1isFalsefor plainEnum. Why does the mixed-in type matter — for equality and for JSON?StrEnum/IntEnummembers arestr/intsubclasses, so==,isinstance, arithmetic andjson.dumpstreat them as primitives; plainEnummembers are opaque objects — compare only to members, rejected by JSON.copy.copy(ticket)thencopy.tags.append("x")— what happens to the original's tags? When do you needdeepcopy?The original'stagsgets"x"too — shallow copy shares mutable attributes. Usedeepcopywhen the copy must be fully independent (nested objects, lists of objects).- List the three patterns from 5.5 and name one place in the AI path each reappears.Strategy → classifier/provider selection (03.11 adapters); adapter → provider wire-format translation (03.11) and
from_dict; registry →CLASSIFIERShere,ToolRegistryin 08A.6, capability registry in 03.11.
Further resources#
- Python docs:
dataclasses— the authoritative reference for every flag and helper - Python docs:
enumand the enum HOWTO — members, flags,_missing_,EnumDict - Python docs:
typing.Protocol— structural typing reference - Python docs:
abc— abstract base classes - PEP 557 — Data Classes — the design rationale
- Real Python: Python Classes and Objects — a deeper OOP tour when you're ready
python3 -c "import dataclasses, enum, inspect; help(dataclasses.dataclass)"— the docs are always onehelp()away
← 01A.5 — Comprehensions, Iterators and Generators | Module 01A overview | 01A.7 — Modules, Packages, Imports and a Tour of the Standard Library →