01A.10 Type Hints and Writing Readable Code

FoundationsLesson 10 of 1112,119 words8 parts
Module 01A · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Every serious Python codebase you will meet in this path — the provider SDKs, Pydantic, FastAPI, the tools you will write for LLM agents — is annotated with type hints: def send(message: str, retries: int = 3) -> bool:. Hints look like Java or TypeScript types, but they behave very differently: Python never enforces them at run time, yet static checkers, IDEs and libraries like Pydantic read them to catch bugs before your code runs and to generate the JSON Schemas that structured output depends on. This lesson teaches the complete typing vocabulary you need to read any annotated signature and write clean hints yourself, then turns to the craft of readable code: naming, small functions, honest comments, ruff, and the refactoring habits that keep a growing project sane. It closes by assembling the support-ticket triage package — typed, formatted and documented — that has been building through Module 01A.

What you'll learn

  • What a type hint is, where annotations live (__annotations__, inspect.signature, get_type_hints), and why Python 3.14 evaluates them lazily
  • The core rule of gradual typing: hints are documentation and checker input, not runtime validation — and how the provider SDKs you will meet (openai, anthropic, google-genai) turn them into signature patterns worth recognising
  • Built-in generics (list[int], dict[str, int]), unions (X | Y, X | None), Optional/Union, Any vs object, Callable, the collections.abc interfaces, Literal, Final, NewType and type aliases (the 3.12 type statement)
  • Describing shapes: TypedDict (with Required/NotRequired/ReadOnly), NamedTuple, dataclass fields, Protocol, generics (TypeVar/Generic and the 3.12 bracket syntax), Self, Annotated, narrowing predicates (TypeGuard, TypeIs, and 3.15's TypeForm), forward references, TYPE_CHECKING, cast, assert_type/assert_never, @overload/@override/NoReturn/reveal_type and # type: ignore
  • How to read an SDK's type hints: a worked walkthrough of the real OpenAI(...) constructor signature, including the NotGiven sentinel and Unpack[...] patterns the SDKs use
  • The static-checker landscape as of November 2026 — mypy, pyright/Pylance, basedpyright, ty and pyrefly — how to run one, how to read its errors, and how to adopt types gradually
  • Readable code: PEP 8 in one page, naming that survives review, guard clauses, comments that explain why, docstrings, ruff lint-and-format, magic numbers, dead code and duplication
  • The Zen of Python, a code-smell table, and a real refactor with an assert-based proof that behaviour didn't change
  • Design for change: pure functions at the core, I/O at the edges, dependency passing, configuration as data, and why global state is a smell
  • Performance sense for freshers: timeit, perf_counter, cProfile, the wins that actually matter, the GIL in one paragraph, and I/O-bound vs CPU-bound work

What you don't need

  • Python beyond 01A.9. If classes, dataclasses, enums, modules and file I/O are still new, do those lessons first — this one assumes you can write them.
  • Any checker installed. Everything here runs on the standard library alone. No API key needed.
  • Pydantic or FastAPI. Module 01B owns those; this lesson only shows where your hints become their schemas.

Setup

You need Python 3.11 or newer and a terminal with a text editor. As of November 2026 the current stable release is Python 3.15.2 (released 25 October 2026), and the supported range is 3.11–3.15; Python 3.10 reached end-of-life on 1 October 2026 (check python.org/downloads for the live table). The quickest way to get a modern Python is uv:

bash
uv python install 3.13
uv run python --version

or install from python.org / your OS package manager and run scripts with python3 script.py. Every snippet in this lesson is standard-library only and deterministic: save it as a .py file and run it. Where a snippet uses a feature newer than 3.11 (type statements, PEP 695 generics, TypeIs, ReadOnly, PEP 696 defaults), the lesson says which version added it and shows the older spelling. The optional static checkers in Part 5 run via uvx — no project setup required — but you can skip that part entirely and still write every hint in this lesson.


What you must be able to do after this lesson#

  • Annotate functions with type hints
  • Explain that hints are not checked at runtime
  • Use unions, Optional, list and dict generics
  • Describe a dict shape with TypedDict or a dataclass
  • Read the type hints of an SDK function
  • Run a static type checker and read its errors
  • Refactor unclear code using guard clauses and good names

Why this matters for an AI engineer#

Type hints are the contract layer of the whole path. Provider SDKs annotate every method; Pydantic turns your annotated classes into validation schemas and JSON Schemas; FastAPI builds whole APIs from function signatures; tool-calling lessons derive parameter schemas from hints. A reader who can't parse str | Callable[[], str] | None can't read the documentation that tells them how to call a model.

You'll hear... You'll understand it after...
"The SDK signature says max_retries: int = DEFAULT_MAX_RETRIES." 4.2 Reading OpenAI.__init__
"Hints aren't checked — why annotate at all?" 1.2 Hints are not validation and Part 5
"Pydantic reads your annotations to build the schema." 3.1 TypedDict and 01B.6
"This field is str | None — nullable but still required." 2.2 Unions and optional values
"Use Literal for the finish reason." 2.3 Any, object, Callable and friends
"response_format wants a TypedDict or a Pydantic model." 3.1 TypedDict and 03.4
"The tool schema is generated from the function's hints." 3.4 Generics and 08A.6
"My custom is_ticket check should narrow the type too." 3.7 Type-narrowing predicates
"mypy says error: Argument 1 has incompatible type." 5.3 Reading checker output
"Why is Any everywhere in the SDK stubs?" 2.3 and 5.4
"Our CI runs ruff check and ruff format." 6.4 ruff: lint and format
"Keep the pure logic free of print and file I/O." 7.1 Pure functions, I/O at the edges
"Profile before you optimise." 8.1 Measure, don't guess

Part 1: Why type hints#

1.1 What an annotation is#

An annotation is an expression you attach to a name — a parameter, a return value, a variable — that says what type of value belongs there. Python stores annotations; it doesn't act on them:

python
# hints_demo.py
def greet(name: str, punct: str = "!") -> str:
    return f"Hello, {name}{punct}"

count: int = 3
items: list[str] = ["a", "b"]

import inspect
print(inspect.signature(greet))
print(greet.__annotations__)
Output2 lines
(name: str, punct: str = '!') -> str
{'name': <class 'str'>, 'punct': <class 'str'>, 'return': <class 'str'>}

Three places the hints live:

  • Source code — what humans and checkers read.
  • __annotations__ — a dict on the function (or module/class) holding the annotation objects.
  • inspect.signature() — reconstructs the full call signature, annotations included; this is what help(), IDEs and pydoc display.

Annotations are ordinary Python expressions evaluated in the module's namespace — list[str] is a real object (types.GenericAlias), str | None is a union object. On Python 3.14 and later they are evaluated lazily (PEP 649, deferred evaluation of annotations): defining def f(x: NotYetDefined) no longer raises NameError at def time; the name is only resolved when something asks for the annotations. On 3.11–3.13 the same code raises immediately unless you quote the forward reference or add from __future__ import annotations (covered in 3.6).

python
# deferred_314.py — run on Python 3.14+
import annotationlib
from typing import get_type_hints

def broken(x: TotallyUndefined) -> None:
    pass

print("def succeeded: annotations were not evaluated")
try:
    broken.__annotations__
except NameError as exc:
    print("accessing __annotations__:", exc)

print(annotationlib.get_annotations(broken, format=annotationlib.Format.FORWARDREF))

class Later: pass
def ok(x: Later) -> Later:
    return x
print(get_type_hints(ok))
Output · the memory address is masked — it varies per run4 lines
def succeeded: annotations were not evaluated
accessing __annotations__: name 'TotallyUndefined' is not defined
{'x': ForwardRef('TotallyUndefined', owner=<function broken at 0x...>), 'return': None}
{'x': <class '__main__.Later'>, 'return': <class '__main__.Later'>}

1.2 Hints are not validation#

This is the single most important fact in the lesson, and the most commonly misunderstood. CPython does not check annotations at run time. Not at call time, not at assignment time, not ever:

python
# not_validation.py
def line_total(price: float, quantity: int) -> float:
    return price * quantity

print(line_total(9.99, 3))    # fine: 29.97
print(line_total("9.99", 3))  # hint ignored: str * int repeats -> '9.999.999.99'

def greet(name: str) -> str:
    return f"Hello, {name.upper()}"

greet(42)  # AttributeError from .upper(), not from a type check

Output (script path shortened to the file name — real tracebacks show the absolute path, and the ~~~~~^^^^ carets need Python 3.11+):

text
29.97
9.999.999.99
Traceback (most recent call last):
  File "not_validation.py", line 11, in <module>
    greet(42)  # AttributeError from .upper(), not from a type check
    ~~~~~^^^^
  File "not_validation.py", line 9, in greet
    return f"Hello, {name.upper()}"
                     ^^^^^^^^^^
AttributeError: 'int' object has no attribute 'upper'

The first call is the dangerous one: "9.99" * 3 is legal Python (string repetition), so the function silently returns a nonsense string. The second fails — but with an AttributeError about .upper(), a confusing message that doesn't say "you passed an int where a str was expected". If you need the wrong value rejected, you need a validator: a type checker, isinstance guards, or Pydantic (01B.6 owns validation properly). Hints make that validation possible; they don't perform it.

1.3 Who reads hints at run time#

If Python ignores them, why write them? Three audiences:

  1. Static checkers and IDEs (Part 5) — they read source (or __annotations__) without running anything.
  2. Library code that introspects — dataclasses reads field annotations to generate __init__; enum, NamedTuple and TypedDict do the same; pydantic turns annotations into validators and JSON Schemas; FastAPI builds request parsing from them; functools.singledispatch and several stdlib helpers dispatch on them.
  3. Humans — the cheapest documentation there is, kept honest by checkers.
python
# dataclass_reads_hints.py
from dataclasses import dataclass, fields

@dataclass
class Ticket:
    id: str
    priority: int = 2

t = Ticket("T-1")
print(t)
for f in fields(Ticket):
    print(f.name, "->", f.type)
Output3 lines
Ticket(id='T-1', priority=2)
id -> <class 'str'>
priority -> <class 'int'>

Field.type holds the annotation object, not its name — for id: str that's the class str itself, printed as <class 'str'>. (With from __future__ import annotations or a quoted hint it would be the string 'str' instead — same mechanism as 1.1.) dataclasses literally reads __annotations__ to know which __init__ parameters to generate — proof that hints are a runtime API, not just comments. The same mechanism is what makes class Movie(TypedDict) produce a JSON-Schema-shaped dict contract in 3.1, and what lets Pydantic inspect exactly these annotation objects to derive {"type": "object", "properties": {...}} from a class in 01B.6.


Part 2: The typing vocabulary#

2.1 Built-in generics#

Since Python 3.9 you write generics with the built-in types themselves — list[int], not typing.List[int]. The older typing.List, typing.Dict, typing.Set, typing.FrozenSet, typing.Tuple spellings still exist for compatibility, but never write them in new code: they are deprecated aliases kept for pre-3.9 readers.

python
# builtin_generics.py
counts: list[int] = [1, 2, 3]
lookup: dict[str, int] = {"a": 1}
pair: tuple[int, ...] = (1, 2, 3)
uniq: set[str] = {"x", "y"}

import typing
from typing import get_args, get_origin
print(get_origin(dict[str, int]), get_args(dict[str, int]))
print(get_origin(tuple[int, ...]), get_args(tuple[int, ...]))

try:
    isinstance([1], list[int])
except TypeError as exc:
    print("isinstance with list[int]:", exc)
print(isinstance([1], list))
Output4 lines
<class 'dict'> (<class 'str'>, <class 'int'>)
<class 'tuple'> (<class 'int'>, Ellipsis)
isinstance with list[int]: isinstance() argument 2 cannot be a parameterized generic
True

Reading the annotations:

Annotation Means Notes
list[int] a list whose items are ints list alone means list[Any]
dict[str, int] str keys → int values two parameters, key then value
tuple[int, str] exactly a 2-tuple (int, str) fixed arity
tuple[int, ...] a tuple of any length of ints the ... is "and so on"
set[str], frozenset[str] sets of strs frozenset is the immutable one
bytes, bytearray raw bytes what files and HTTP bodies give you

2.2 Unions and optional values#

A union says "one of these types". Python 3.10 added the X | Y spelling (it mirrors Optional/Union but reads better):

python
# unions.py
def find_user(user_id: int) -> dict | None:
    return {"id": user_id} if user_id > 0 else None

def describe(value: int | str | None) -> str:
    return f"{value!r} is {type(value).__name__}"

from typing import Optional, Union, get_args, get_origin
print(type(int | None))
print(get_origin(int | str), get_args(int | str))
print(get_origin(Optional[int]), get_args(Optional[int]))
print(get_origin(Union[int, str]), get_args(Union[int, str]))
Output4 lines
<class 'typing.Union'>
<class 'typing.Union'> (<class 'int'>, <class 'str'>)
<class 'typing.Union'> (<class 'int'>, <class 'NoneType'>)
<class 'typing.Union'> (<class 'int'>, <class 'str'>)

Key facts:

  • X | None means "X, or None" — the modern spelling of Optional[X]. Both produce the same union (get_args(Optional[int]) is (int, NoneType)). Optional and Union still appear in older code and in SDK stubs; read them, don't write them.
  • X | Y | Z is a union of any size. int | str accepts either.
  • None is a value, NoneType is its type. In annotations you write None (or NoneType); the union stores NoneType. Check x is None, never x == None.
  • A union is a promise the value is one of these — Python doesn't narrow it for you at run time, but checkers do "type narrowing": after if x is None: return, the checker knows x isn't None below.
You see It means Write instead
Optional[X] X | None X | None (3.10+)
Union[X, Y] X | Y X | Y
Union[X, Y, None] X | Y | None same
Optional[Union[X, Y]] X | Y | None flatten it

2.3 Any, object, Callable, the ABCs, Literal, Final, NewType#

These are the special forms you'll meet constantly in SDK signatures:

python
# special_forms.py
import collections.abc
import typing
from typing import Any, Callable, Final, Literal, NewType

def show(value: Any) -> str:
    return f"{value!r} ({type(value).__name__})"

def identity(obj: object) -> object:
    return obj

def apply(fn: Callable[[int], int], x: int) -> int:
    return fn(x)

print(show(1), show("x"), show(None), show([1]))
print(identity({"a": 1}))
print(apply(lambda n: n * 2, 21))
print(isinstance([], collections.abc.Sequence), isinstance("s", collections.abc.Sequence))
print(isinstance({}, collections.abc.Mapping), isinstance(len, collections.abc.Callable))
try:
    isinstance([1], typing.Sequence[int])
except TypeError as exc:
    print("isinstance Sequence[int]:", exc)

mode: Literal["fast", "slow"] = "fast"
LIMIT: Final = 100
UserId = NewType("UserId", int)
print(mode, LIMIT, UserId(7), type(UserId(7)).__name__)
Output7 lines
1 (int) 'x' (str) None (NoneType) [1] (list)
{'a': 1}
42
True True
True True
isinstance Sequence[int]: Subscripted generics cannot be used with class and instance checks
fast 100 7 int
Form Means When to use
Any "any type; the checker stops looking here" Escape hatch — see 5.4
object "some object, but you must narrow before use" Safer than Any: checkers force you to narrow
Callable[[int], int] a function (int) -> int Callbacks, key= functions, Callable[..., T]
Iterable[T], Iterator[T], Sequence[T], Mapping[K, V] the behaviour interfaces Prefer these over list/dict in signatures: accept more inputs
Literal["a", "b"] exactly these values Enums-by-string, mode: Literal["json", "csv"]
Final assign once, never change Constants: MAX_RETRIES: Final = 3
NewType("UserId", int) a distinct int flavour Prevents mixing UserId and OrderId at check time

Notes that matter:

  • Any vs object: Any disables checking in both directions (you can pass anything, get anything back). object is honest — every value is an object, but you can't call .strip() on it without narrowing first. Prefer object when you truly don't know; reach for Any only at boundaries (JSON, **kwargs, third-party stubs).
  • Callable syntax: Callable[[Arg1, Arg2], Return] — the argument list is a list, the return is second. Callable[..., T] means "any arguments, returns T". For richer signatures use ParamSpec (3.4).
  • The ABCs live in collections.abc (and are re-exported by typing for annotations). Sequence[str] accepts list, tuple, str, range; Mapping accepts dict. isinstance works with the unsubscripted ABC (isinstance(x, collections.abc.Sequence) → True), never the subscripted form.
  • Literal is how you say "one of exactly these strings/ints/bools" without an Enum — perfect for mode, format, finish_reason-style fields.
  • NewType is free at run time: UserId(7) is the int 7 (see output — type is int). It's purely a checker-level distinction, like a typedef in C.
  • Final tells checkers "don't reassign this" — it doesn't freeze the object (a Final list can still be mutated).

2.4 Aliases: type statements and TypeAlias#

When a type gets long, name it:

python
# aliases.py
import typing
from collections.abc import Callable

type UserId = int
type Point = tuple[float, float]
type Handler = Callable[[int], str]

UserIdOld: typing.TypeAlias = int
Implicit = dict[str, typing.Any]

print(UserId, type(UserId).__name__)
print(UserId.__value__)
p: Point = (1.0, 2.0)
uid: UserId = 42
print(p, uid, UserIdOld, Implicit)
Output3 lines
UserId TypeAliasType
<class 'int'>
(1.0, 2.0) 42 <class 'int'> dict[str, typing.Any]
  • type X = ... (Python 3.12+, PEP 695) creates a real TypeAliasType object — lazily evaluated, so recursive aliases like JSON trees work: type Json = dict[str, Json] | list[Json] | str | int | float | bool | None. This is the modern spelling.
  • X: TypeAlias = ... is the explicit older marker; a bare assignment (Implicit = dict[str, Any]) also works as an implicit alias — checkers treat simple assignments as aliases too.
  • Aliases are for readability, not new types: UserId and int are interchangeable to the checker (unlike NewType).

Part 3: Describing shapes#

Functions take and return scalars; real code moves records — a ticket, a message, an API response. Three tools describe record shapes, and choosing between them is a daily decision.

Tool What it describes Runtime behaviour Best for
TypedDict a dict with known keys is a plain dict; keys aren't checked JSON-shaped data, API payloads, **kwargs unpacking
NamedTuple an immutable tuple with field names a real tuple subclass tiny fixed records, return values
dataclass a class with generated methods a real class your own domain objects (see 01A.6)

3.1 TypedDict#

A TypedDict declares the keys and value types of a dictionary. At run time it is a dict — construction doesn't validate anything:

python
# typeddict_demo.py
from typing import NotRequired, Required, TypedDict

class Movie(TypedDict):
    title: str
    year: int
    director: str | None

class MoviePartial(TypedDict, total=False):
    title: str
    year: int

class MovieStrict(TypedDict):
    title: Required[str]
    year: Required[int]
    director: NotRequired[str | None]

m = Movie(title="Dune", year=2021, director=None)
print(type(m), m)
print("required:", sorted(Movie.__required_keys__))
print("optional:", sorted(Movie.__optional_keys__))
print("total:", Movie.__total__)

p = MoviePartial(title="Only title")
print(p, sorted(MoviePartial.__required_keys__))

s = MovieStrict(title="Dune", year=2021)
print(s, sorted(MovieStrict.__required_keys__), sorted(MovieStrict.__optional_keys__))

bad = Movie(title=123, year="x")  # type: ignore[arg-type]
print(bad)
Output7 lines
<class 'dict'> {'title': 'Dune', 'year': 2021, 'director': None}
required: ['director', 'title', 'year']
optional: []
total: True
{'title': 'Only title'} []
{'title': 'Dune', 'year': 2021} ['title', 'year'] ['director']
{'title': 123, 'year': 'x'}

Reading it:

  • Movie(title="Dune", year=2021, director=None) returns a plain dict — type(m) is dict. m["title"] works; m.title does not.
  • Every key is required by default (__required_keys__), even director: str | None — | None means "value may be None", not "key may be absent". That's the same nullable-vs-omittable trap Pydantic users hit (03.4 §2.4).
  • total=False makes all keys optional; Required[...]/NotRequired[...] (3.11+) override per key — mix them freely.
  • ReadOnly[...] (3.13+) marks a key checkers shouldn't let you assign to — for "computed" fields in API responses.
  • Python 3.15 adds closed=True and extra_items=T class arguments (PEP 728): closed rejects unknown keys statically, extra_items types the catch-all remainder — the TypedDict answer to "open vs closed objects". On 3.11–3.14 there is no spelling for this — document the expected key set and rely on review, or enforce it at a validation boundary (Pydantic extra="forbid" in 01B.6).
  • Inheritance works like dict merging: class MovieStrict(Movie) adds keys; total=False on the child only affects the child's own keys.

Where TypedDicts shine in this path: JSON-shaped data your code passes around — API request bodies, tool_calls[].function.arguments after json.loads, config files, the usage object. They cost nothing at run time and document intent perfectly.

3.2 NamedTuple, and when a dataclass wins#

typing.NamedTuple gives tuple fields names — immutable, unpackable, cheap:

python
# namedtuple_demo.py
from typing import NamedTuple

class Point(NamedTuple):
    x: float
    y: float = 0.0

p = Point(1.0, 2.0)
print(p, p.x, p.y)
print(p._asdict())
print(isinstance(p, tuple), len(p))
a, b = p
print(a, b)
Output4 lines
Point(x=1.0, y=2.0) 1.0 2.0
{'x': 1.0, 'y': 2.0}
True 2
1.0 2.0
  • Fields are positional-or-keyword, defaults allowed (y: float = 0.0), _asdict()/_replace()/_make() helpers included.
  • Because it's a tuple, it unpacks (a, b = p), compares by value, and can be a dict key. Fields can't be reassigned — and the immutability is shallow: class P(NamedTuple): xs: list is legal and p.xs.append(1) works, exactly like a plain tuple holding a list. Methods are fine to add; what you can't do is mutate a field or change the tuple layout.

Decision rule: use NamedTuple for tiny fixed records (coordinates, RGB triples, (name, score) pairs); use @dataclass for anything with behaviour, defaults that need field(default_factory=...), or mutation. dataclass is almost always the right answer for domain objects — the triage package's Ticket is one.

3.3 Protocol: structural typing#

A Protocol says "anything with these methods fits" — no inheritance required. It's how the path describes "a model that can .generate()" or "a store that can .save()" without forcing a base class:

python
# protocol_demo.py
from typing import Protocol, runtime_checkable

class HasId(Protocol):
    @property
    def id(self) -> str: ...

@runtime_checkable
class Sized2(Protocol):
    def __len__(self) -> int: ...

def describe(obj: HasId) -> str:
    return f"object {obj.id}"

class Ticket:
    def __init__(self, ticket_id: str) -> None:
        self.id = ticket_id

print(describe(Ticket("T-1")))
print(isinstance([1, 2], Sized2), isinstance(5, Sized2))
try:
    isinstance([1], HasId)
except TypeError as exc:
    print("non-runtime protocol:", exc)
Output3 lines
object T-1
True False
non-runtime protocol: Instance and class checks can only be used with @runtime_checkable protocols
  • Ticket never mentions HasId, yet describe(Ticket(...)) type-checks — Ticket has .id: str, so it structurally satisfies the protocol. That's duck typing made checkable.
  • @runtime_checkable enables isinstance/issubclass — but only checks method presence, not signatures. Non-runtime protocols raise TypeError on isinstance (real output above).
  • Protocol members use ... as the body — they're declarations, not implementations.
  • In this path: provider interfaces (03.11), the VectorStore/Embedder protocols in 06, tool registries in 08A.6. 01A.6 covers writing them; here the point is reading class X(Protocol) in SDK stubs.

3.4 Generics: TypeVar, Generic, and the new syntax#

Generics let one function or class work with many types while keeping the relationship: def first(xs: list[T]) -> T — the same T goes in and comes out.

python
# generics_demo.py
from collections.abc import Callable
from typing import Generic, Self, TypeVar

T = TypeVar("T")

class OldBox(Generic[T]):
    def __init__(self, item: T) -> None:
        self.item = item
    def get(self) -> T:
        return self.item

b = OldBox(3)
print(b.get())

# --- Python 3.12+ (PEP 695): brackets instead of TypeVar boilerplate
def first_new[T](xs: list[T]) -> T:
    return xs[0]

class NewBox[T]:
    def __init__(self, item: T) -> None:
        self.item = item
    def get(self) -> T:
        return self.item
    def clone(self) -> Self:
        return NewBox(self.item)

print(first_new([1, 2]), first_new(["a", "b"]))
nb = NewBox("hi")
print(nb.get(), nb.clone().get(), type(nb.clone()).__name__)

# TypeVar with a default (3.13+, PEP 696)
D = TypeVar("D", default=int)
def wrap[T2 = str](x: T2) -> T2:
    return x
print(wrap(1), wrap("a"), D.__default__)
Output4 lines
3
1 a
hi hi NewBox
1 a <class 'int'>
  • Classic spelling (3.11-compatible, still everywhere): T = TypeVar("T"), then class Box(Generic[T]) or def f(x: T) -> T. Variance (covariant=True, contravariant=True) matters for checkers, rarely for you.
  • New spelling (3.12+): def first[T](xs: list[T]) -> T and class Box[T] — the type parameter is declared in brackets; no TypeVar import needed. Self (3.11+) means "this same class" — clone(self) -> Self returns NewBox, not a hardcoded name.
  • Defaults (3.13+): TypeVar("D", default=int) or def wrap[T2 = str] — the parameter falls back to str when not inferable.
  • ParamSpec, TypeVarTuple, Unpack handle arbitrary signatures — you'll see them in SDK stubs for **kwargs passthrough (e.g. **kwargs: Unpack[HttpxSendArgs] in the OpenAI SDK, 4.3). You rarely write them; you must recognise them.
  • assert_never is the exhaustiveness helper: in the final else of a union dispatch, assert_never(x) tells the checker "nothing should reach here" — it raises AssertionError at run time if it does.
python
# annotated_cast.py
import typing
from typing import Annotated, Any, assert_never, assert_type, cast

PositiveInt = Annotated[int, "must be > 0", {"ge": 1}]
print(PositiveInt.__metadata__)
print(typing.get_args(PositiveInt))
print(cast(int, "not really an int"))
print(assert_type(5, int))

def handle(state: str) -> str:
    if state == "ok":
        return "fine"
    assert_never(state)  # type: ignore[arg-type]
    return "unreachable"

try:
    handle("weird")
except AssertionError:
    print("assert_never raised AssertionError")
Output5 lines
('must be > 0', {'ge': 1})
(<class 'int'>, 'must be > 0', {'ge': 1})
not really an int
5
assert_never raised AssertionError
  • Annotated[T, meta...] attaches arbitrary metadata to a type — __metadata__ holds it. Pydantic, FastAPI and pydantic.Field constraints use this channel (01B.6 §2.4). The base type is still T; the metadata is for tools that understand it.
  • cast(T, value) returns value unchanged — it tells the checker "trust me, this is T". Use it only when the checker can't see what you know (e.g. after isinstance narrowing it can't follow). It performs no conversion and no check.
  • assert_type(value, T) also returns value — its job is to make the checker verify the inferred type equals T. It's a self-test for tricky generics.
  • assert_never(x) raises AssertionError at run time and tells checkers x should be Never — the "impossible" branch marker.

3.5 TypedDict vs dataclass vs dict — the daily choice#

You have... Use Because
JSON from an API / json.loads result TypedDict it is the dict; zero conversion
Your own domain object with behaviour @dataclass methods, validation hooks, asdict()
Tiny immutable record NamedTuple unpacking, hashing, free __init__
Arbitrary key/value bag plain dict[str, Any] honest about uncertainty

The trap to avoid: wrapping every dict in a dataclass "for types" when the dict never leaves JSON-land. TypedDict describes it; dataclass would force conversion code at every boundary.

3.6 Forward references, TYPE_CHECKING and get_type_hints#

Forward references are annotations naming things defined later in the file (or in a module imported only for typing). Three mechanisms, version-dependent:

python
# forward_refs.py
from typing import TYPE_CHECKING, get_type_hints

if TYPE_CHECKING:
    from pathlib import Path   # imported only for type checkers

def size_of(path: "Path") -> int:
    return path.stat().st_size

try:
    get_type_hints(size_of)
except NameError as exc:
    print("get_type_hints:", exc)
Output1 line
get_type_hints: name 'Path' is not defined
  • if TYPE_CHECKING: (from typing) is True for checkers, False at run time — the idiom for "import this only so annotations resolve, never pay the import cost". Circular imports are the usual reason. (Python 3.15 adds a second tool for the cost half of that problem: explicit lazy imports, lazy import json at module level (PEP 810), which load the module on first use. They are for startup time; TYPE_CHECKING remains the tool for names that must never be imported at run time, and neither exists on 3.11–3.14.)
  • Quoted annotations ("Path") defer evaluation on 3.11–3.13; on 3.14+ they're unnecessary — PEP 649 makes all annotations lazy, so def f(x: Path) is fine even before Path exists (as long as it's defined before anyone calls get_type_hints).
  • from __future__ import annotations (top of file) stringifies all annotations on ≤3.13 — cheap insurance for forward refs, and it makes __annotations__ return strings (see 1.1). On 3.14 it is unnecessary for forward references, but it still changes the format: annotations stay strings instead of being lazily evaluated — the NameError-on-access behaviour in the 1.1 demo would not occur with the import present.
  • get_type_hints(fn) resolves strings/lazy annotations to real objects — and will raise NameError for names that don't exist at run time (like our TYPE_CHECKING-only Path). That's the contract: hints referencing checker-only imports can't be introspected at run time — which is exactly why Pydantic models need real imports, not TYPE_CHECKING ones.
  • inspect.signature vs get_type_hints: signature shows annotations as written (strings stay strings, lazy ones may show unevaluated); get_type_hints forces evaluation. SDK docs and IDEs show the resolved form.

3.7 Type-narrowing predicates: TypeGuard, TypeIs and TypeForm#

isinstance narrows built-in and collections.abc types — but it can't check a TypedDict or any "shape" type, because those aren't runtime classes. When you parse untrusted JSON and want the checker to treat the result as a TicketPayload, you write a type predicate: a function that returns a boolean and declares what True means. Two special forms annotate the return type:

  • TypeGuard[T] (3.10+) — narrows only the True branch: inside if is_ticket(x):, x is T; the else branch learns nothing.
  • TypeIs[T] (3.13+, PEP 742) — narrows both branches: True narrows to the intersection of the input type and T, False excludes T. This is the recommended spelling; use TypeGuard only when you deliberately want one-way narrowing (e.g. narrowing list[object] to list[int], which TypeIs forbids because the types aren't cleanly nested). On 3.10–3.12, TypeIs is available from typing_extensions.
  • TypeForm[T] (3.15, PEP 747) — the mirror image: for functions that accept a type expression as an argument (def cast[T](typ: TypeForm[T], value) -> T). At run time TypeForm(x) returns x unchanged; it exists so signatures can say "this parameter is a type". You'll meet it in 3.15+ library code; it has no runtime effect to demo.
python
# typeis_demo.py — run on Python 3.13+ (TypeIs lives in typing since 3.13)
from typing import TypedDict, TypeIs

class TicketPayload(TypedDict):
    id: str
    subject: str

def is_ticket_payload(obj: object) -> TypeIs[TicketPayload]:
    """Type predicate: True only for dicts shaped like a ticket payload."""
    return (
        isinstance(obj, dict)
        and isinstance(obj.get("id"), str)
        and isinstance(obj.get("subject"), str)
    )

def handle(data: TicketPayload | list[str] | None) -> str:
    if is_ticket_payload(data):
        return f"ticket {data['id']}: {data['subject']}"
    if data is None:
        return "no data"
    return f"{len(data)} non-ticket items"

print(handle({"id": "T-1", "subject": "Printer offline"}))
print(handle(["a", "b"]))
print(handle(None))
print(handle({"unexpected": "shape"}))
Output4 lines
ticket T-1: Printer offline
2 non-ticket items
no data
1 non-ticket items

What the checker sees (nothing here runs differently — the predicates are plain functions):

  • In the if branch, data is narrowed to TicketPayload, so data["id"] is a str — even though is_ticket_payload is user code the checker can't see inside.
  • In the else branches, TicketPayload is excluded from data's type — that's the TypeIs advantage over TypeGuard, which would leave data as TicketPayload | list[str] | None there.
  • The contract is a promise, like every hint: if is_ticket_payload returned True for a non-dict, the checker would believe a lie. Keep predicates honest — they're your isinstance for shapes.
  • The last demo call, handle({"unexpected": "shape"}), is deliberately wrong: that dict is neither a TicketPayload nor a list[str], so a checker would flag the call. Python itself runs it, falls through to the final return, and len(data) counts the dict's one key — the "1 non-ticket items" line, a small reminder that hints don't validate (1.2).

This is the pattern 01B.6 builds on: Pydantic's TypeAdapter.validate_python is a runtime check, and TypeIs predicates are how you narrow SDK/JSON payloads into typed shapes before they reach it.

3.8 @overload, @override, NoReturn and reveal_type#

Four more forms you will meet in SDK stubs, and one you will use daily when a checker puzzles you. All of them are promises to a checker; none changes what the program does.

  • @overload declares several call shapes for one function, each with its own return type. The real SDKs use it heavily: client.responses.create(...) in openai-python has separate @overload signatures for stream=False (returns a Response) and stream=True (returns a stream of events), so the checker knows what you get back from the flag you pass (as of November 2026, read from src/openai/resources/responses/responses.py on GitHub). Stacked @overload stubs have ... bodies; one final, undecorated definition holds the real code.
  • @override (3.12+, typing_extensions.override before that) marks a method as intentionally replacing a parent's. If someone renames the parent method later, a checker flags the child as overriding nothing. The OpenAI client source uses it, for example on its base_url property; at run time it only sets __override__ = True.
  • NoReturn (and its synonym Never, 3.11+) is the return type of a function that never returns normally: it always raises or exits. After calling it, a checker treats the code below as unreachable, which is how sys.exit() is typed.
  • reveal_type(expr) asks the checker "what type do you infer here?" and prints it in its output. At run time (3.11+) it just prints Runtime type is '...' to stderr and returns the value, so delete it afterwards. It is the fastest way to see why a checker is unhappy.
python
# overload_demo.py — @overload, @override and NoReturn: checker-only promises
from typing import Literal, NoReturn, get_overloads, overload, override, reveal_type

class Response: ...
class EventStream: ...

@overload
def create(*, stream: Literal[False] = False) -> Response: ...
@overload
def create(*, stream: Literal[True]) -> EventStream: ...
def create(*, stream: bool = False) -> Response | EventStream:
    # the one real implementation; the two stubs above exist only for checkers
    return EventStream() if stream else Response()

print(type(create()).__name__, type(create(stream=True)).__name__)
print("overloads registered:", len(get_overloads(create)))
reveal_type(create(stream=True))      # a checker shows EventStream; at run time it just prints

class Base:
    def run(self) -> str:
        return "base"

class Child(Base):
    @override                           # a checker flags this if Base.run is renamed
    def run(self) -> str:
        return "child"

print(Child().run(), Child.run.__override__)

def fail(msg: str) -> NoReturn:         # promise: this function never returns normally
    raise SystemExit(msg)

Output (the reveal_type line goes to stderr, so it can appear first when the two streams are shown together; needs Python 3.12+ because of override):

text
Runtime type is 'EventStream'
Response EventStream
overloads registered: 2
child True

When you hover over client.responses.create(...) in an editor and see different return types for different arguments, this is the mechanism. When you write a function whose return type depends on a flag, @overload with Literal[True]/Literal[False] is the honest signature; the alternative, -> Response | EventStream, forces every caller to narrow the result by hand.


Part 4: Reading an SDK's type hints#

You will spend real time reading provider SDK signatures — they are the documentation. Here's how to decode one fast.

4.1 inspect.signature is your decoder#

python
# signature_demo.py — SDK-style signature, local stand-in
import inspect
from collections.abc import Callable, Mapping
from typing import Any

class NotGiven:
    pass

not_given = NotGiven()

def create_client(
    *,
    api_key: str | Callable[[], str] | None = None,
    base_url: str | None | Any = not_given,
    timeout: float | None = 600.0,
    max_retries: int = 2,
    default_headers: Mapping[str, str] | None = None,
) -> "Client":
    return Client()

class Client:
    pass

sig = inspect.signature(create_client)
print(sig)
for name, param in sig.parameters.items():
    print(f"  {name}: default={param.default!r} kind={param.kind}")
print("return:", sig.return_annotation)
Output · the NotGiven object's address varies — illustrative shape7 lines
(*, api_key: str | collections.abc.Callable[[], str] | None = None, base_url: str | None | Any = <__main__.NotGiven object at 0x...>, timeout: float | None = 600.0, max_retries: int = 2, default_headers: collections.abc.Mapping[str, str] | None = None) -> 'Client'
  api_key: default=None kind=KEYWORD_ONLY
  base_url: default=<__main__.NotGiven object at 0x...> kind=KEYWORD_ONLY
  timeout: default=600.0 kind=KEYWORD_ONLY
  max_retries: default=2 kind=KEYWORD_ONLY
  default_headers: default=None kind=KEYWORD_ONLY
return: Client

Reading it left to right:

  • * first → every parameter is keyword-only: you must write create_client(api_key=...), never positional. SDK constructors are all keyword-only — that's why the call sites in 03.1 always use name=.
  • str | Callable[[], str] | None → "a string, a zero-arg function returning a string (for refreshing tokens), or None (read OPENAI_API_KEY)". Three-way unions are normal in SDKs.
  • -> "Client" → the return annotation is a string — a forward reference, because Client is defined after the function. inspect.signature shows it as written; get_type_hints would resolve it.
  • kind=KEYWORD_ONLY confirms the *; param.default tells you what's optional.

4.2 Reading OpenAI.__init__ for real#

Here's the actual constructor signature from openai-python (the OpenAI class in src/openai/_client.py, read from the project source on GitHub at the tag v3.42.1, the version the path's samples were checked against, on 11 November 2026; later releases may add or reorder parameters, so treat the exact list as a snapshot):

python
# Excerpt from openai-python src/openai/_client.py (lightly trimmed)
def __init__(
    self,
    *,
    api_key: str | Callable[[], str] | None = None,
    admin_api_key: str | None = None,
    workload_identity: WorkloadIdentity | X509WorkloadIdentity | None = None,
    organization: str | None = None,
    project: str | None = None,
    webhook_secret: str | None = None,
    provider: _Provider | None = None,
    base_url: str | httpx2.URL | None | NotGiven = not_given,
    data_residency: DataResidency | None = None,
    websocket_base_url: str | httpx2.URL | None = None,
    timeout: float | Timeout | None | NotGiven = not_given,
    max_retries: int = DEFAULT_MAX_RETRIES,
    default_headers: Mapping[str, str] | None = None,
    default_query: Mapping[str, object] | None = None,
    http_client: httpx2.Client | None = None,
    _strict_response_validation: bool = False,
    _enforce_credentials: bool = True,
) -> None:
    ...  # body omitted

Decode it with the vocabulary from Parts 2–3:

Parameter Annotation says What it means for you
api_key str | Callable[[], str] | None string key, a callable that mints fresh keys, or None → env var
base_url str | httpx2.URL | None | NotGiven four-way union including the NotGiven sentinel — "argument omitted" is different from None
timeout float | Timeout | None | NotGiven seconds as float, or an httpx2.Timeout object
max_retries int = DEFAULT_MAX_RETRIES a module constant — the default lives in one place
default_headers Mapping[str, str] | None accept any mapping, not just dict — the ABC pays off
http_client httpx2.Client | None dependency injection: pass your own HTTP client
_strict_response_validation, _enforce_credentials bool leading underscore = private; you can pass them but shouldn't

4.3 Sentinels, TYPE_CHECKING and typed **kwargs#

The same file shows the other patterns you must recognise:

python
# Real lines from the same file (abridged)
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Mapping, Callable, Iterable, Awaitable, cast
from typing_extensions import Self, Unpack, override
import httpx2 as httpx2

if TYPE_CHECKING:
    from .resources import responses as _responses   # heavy imports deferred
    ...

class OpenAI(SyncAPIClient):
    @cached_property
    def responses(self) -> Responses: ...           # built lazily on first use

    def _send_with_auth_retry(
        self, request: httpx2.Request, *,
        stream: bool, retried: bool = False,
        **kwargs: Unpack[HttpxSendArgs],           # kwargs typed as a TypedDict
    ) -> httpx2.Response: ...
  • from __future__ import annotations at the top — the SDK stringifies every annotation so the file never evaluates them eagerly (cheap startup, no forward-ref crashes).
  • TYPE_CHECKING block — dozens of resource classes imported only for checkers; the real imports happen lazily inside cached_property methods. This is the 3.6 idiom at industrial scale.
  • typing_extensions — Self, Unpack, override come from the backport package so the SDK supports older Pythons; on 3.11+ Self/override also exist in typing.
  • Unpack[HttpxSendArgs] on **kwargs — PEP 692 lets a TypedDict type the keys of **kwargs. When you see **kwargs: Unpack[SomeDict], the dict's keys are the allowed keyword arguments.
  • httpx2 — the SDKs switched to Pydantic's httpx2 fork (03.1 §4.5); httpx2.Client, httpx2.URL, httpx2.Request are the HTTP types in signatures.

The anthropic and google-genai SDKs use the same conventions (base_url=, timeout=, max_retries=, default_headers=, http_client=) with different names for credential sources — the comparison table is in 03.1 §7.1.


Part 5: Static type checkers#

Hints only pay off when something reads them. That's the checker's job.

5.1 The landscape, as of November 2026#

Checker Who Latest (Nov 2026) Status Strengths Run it
mypy Jukka Lehtosalo & co (python/mypy) 2.4.1 stable, the original strictest, most configurable, huge docs uvx mypy
pyright Microsoft 1.1.414 (via pyright PyPI wrapper) stable fast, powers Pylance in VS Code uvx pyright
Pylance Microsoft ships with VS Code stable the IDE experience most Python devs see VS Code extension
basedpyright detachhead (community) 1.40.2 stable pyright + more rules, better defaults uvx basedpyright
ty Astral (Ruff/uv makers) 0.0.101 beta 10–100× faster, Rust, uvx ty check uvx ty check
pyrefly Meta 1.4.1 stable very fast, Instagram-scale proven uvx pyrefly check

The honest summary: mypy and pyright are the safe defaults — every tutorial, every types- stub package and every "strict mode" guide assumes one of them. ty and pyrefly are the new fast generation — dramatically quicker, still closing feature gaps (ty is explicitly beta with a 0.0.x versioning policy; check their tracking issues before betting a codebase on them). basedpyright sits between: pyright-compatible with saner defaults and more opinionated rules. For this path, the recommendation is: learn mypy or pyright first (the errors are interchangeable in spirit), try ty for speed on big repos, and let your editor's language server (Pylance or basedpyright) do the live checking.

5.2 Running one#

No install needed — uvx fetches and runs the tool ephemerally:

bash
uvx mypy src/                 # or: uvx --from mypy mypy src/
uvx pyright src/              # needs Node.js under the hood
uvx ty check                  # Astral's checker; `ty check` is the subcommand
uvx pyrefly check             # Meta's checker

Or add it as a dev dependency so the version is recorded in your project's lockfile (Module 01B.1 covers uv add --dev properly):

toml
# pyproject.toml — the [tool.*] sections each checker reads
[tool.mypy]
python_version = "3.13"
strict = true
warn_return_any = true

[tool.pyright]
typeCheckingMode = "standard"   # "off" | "basic" | "standard" | "strict"
pythonVersion = "3.13"

Checkers read pyproject.toml, mypy.ini, setup.cfg or their own config file — mypy --config-file, pyright's pyrightconfig.json. VS Code users get live squiggles from Pylance (Microsoft's pyright-based extension, bundled with the Python extension) or the basedpyright extension — the CLI and the IDE speak the same rules.

5.3 Reading checker output#

A typical mypy error:

text
# Example output (illustrative — exact wording varies by checker/version)
src/triage/io.py:42: error: Argument 1 to "_row_to_ticket" has incompatible type "dict[str, str]"; expected "Mapping[str, object]"  [arg-type]
src/triage/report.py:18: error: Unsupported operand types for + ("int" and "str")  [operator]
Found 2 errors in 2 files (checked 7 source files)

The anatomy: file:line: error: <what's wrong> [<error-code>]. The error code (arg-type, operator, union-attr, return-value, assignment, call-arg, import-untyped...) is the part to learn — each has a docs page and a typical fix. uvx mypy --show-error-codes (on by default in recent versions) and --show-column-numbers help; # type: ignore[code] suppresses one specific code on one line — use it sparingly and always with the code, never a bare # type: ignore.

Strictness is a dial, not a switch. mypy's --strict bundle (or strict = true) enables ~20 flags at once — disallow_untyped_defs, disallow_any_generics, warn_return_any, no_implicit_optional, strict_equality, extra_checks... You will not pass strict on a real codebase day one. The professional adoption path:

  1. Annotate new code fully; run the checker on your package only.
  2. Fix errors in files you touch; leave the rest.
  3. Ratchet: enable one strict flag at a time (disallow_untyped_defs first — it forces signatures).
  4. # type: ignore[code] with a comment for genuine dynamic boundaries; cast for checker-blind spots; Any at JSON edges only.

Libraries without hints. The error code import-untyped (mypy) or "stub file not found" (pyright) means the library ships no type information. A package opts in by shipping a py.typed marker (PEP 561); for those that don't, the community publishes stub-only packages named types-<name> (for example types-requests), which you add as a dev dependency. The provider SDKs and Pydantic ship their own types, so you rarely need stubs for them; for a genuinely untyped dependency, # type: ignore[import-untyped] on the import line is the honest, searchable opt-out.

5.4 What typing does not do#

  • No runtime validation. x: int = "five" still runs; only a checker (or Pydantic/isinstance) catches it. The line_total("9.99", 3) bug from 1.2 sails through every checker that isn't looking at the call site — and even then, only if the call is annotated.
  • No enforcement of Final, Literal, ReadOnly — they're advisory.
  • No performance cost worth mentioning — annotations are lazy objects; the type statement and generics add nanoseconds at def time, nothing per call.
  • Any is a hole, not a type. Every Any you write is a place bugs can hide; every Any you read in SDK stubs is a place the SDK authors punted to you.

The bridge to real validation is 01B.6: Pydantic consumes your annotations and enforces them at run time — class Ticket(BaseModel) with id: str rejects id=123 with a ValidationError. Hints describe; Pydantic polices. You'll use both constantly.


Part 6: Writing readable code#

Type hints describe what code does; readable code makes it obvious how. These are the habits that separate "works" from "maintainable" — the difference reviewers and future-you actually feel.

6.1 PEP 8 in one page#

PEP 8 is the style guide; you don't memorise it, you let ruff enforce it (6.4). The parts worth internalising:

  • 4 spaces per indent, 79–88 columns per line (ruff's default line length is 88), two blank lines between top-level defs, one between methods.
  • snake_case for functions/variables/modules, PascalCase for classes, UPPER_CASE for constants.
  • Imports at the top, grouped: stdlib → third-party → local, one per line, alphabetised (ruff's I rules fix this for you).
  • Whitespace: around binary operators, after commas, never inside brackets unnecessarily; no space before : in slices (x[1:5]).
  • Trailing commas in multi-line literals — they make diffs cleaner and ruff format happy.

Naming that survives review: names should answer "what is this?" at the point of use. tickets_to_classify beats data; urgent_open_ids beats res. Booleans read as questions: is_urgent, has_paid, should_retry — never flag or status2. Include units in names where they matter: timeout_seconds, price_cents, max_tokens — the SDKs do exactly this (max_retries, timeout, max_output_tokens). Avoid l, O, I single letters outside tiny comprehensions; avoid abbreviations that need a decoder ring (msg, cfg, tmp are fine locally, not across a module boundary).

6.2 Functions: length, early returns, flat is better than nested#

The rules of thumb that hold up in review:

  • One job per function. If the docstring needs "and", split it. Aim for ~20–40 lines; past ~60 it's usually two functions.
  • Return early. Guard clauses put the "can't happen" cases first and keep the happy path unindented at the bottom — the single biggest readability win in Python.
  • Max ~3 levels of nesting. Deeper means extract a function or invert the condition.
  • Parameters: ≤5 positional is comfortable; more means a dataclass/TypedDict "options" object or keyword-only args. Boolean positional flags (f(x, True)) are a smell — make them keyword-only or an enum.
  • Don't repeat yourself — but don't abstract too early either. Two similar lines are fine; the third copy is the refactor signal.
python
# guard_clauses.py — same behaviour, flat vs nested
def old_way(user):
    result = None
    if user is not None:
        if user.is_active:
            if user.age >= 18:
                result = "eligible"
            else:
                result = "too young"
        else:
            result = "inactive"
    else:
        result = "no user"
    return result

def new_way(user):
    if user is None:
        return "no user"
    if not user.is_active:
        return "inactive"
    if user.age < 18:
        return "too young"
    return "eligible"

class U:
    def __init__(self, age, active=True):
        self.age = age
        self.is_active = active

cases = [None, U(30), U(16), U(30, active=False)]
print([old_way(u) for u in cases])
print([new_way(u) for u in cases])
assert [old_way(u) for u in cases] == [new_way(u) for u in cases]
print("identical")
Output3 lines
['no user', 'eligible', 'too young', 'inactive']
['no user', 'eligible', 'too young', 'inactive']
identical

The new_way version reads top-to-bottom as a checklist of rejection reasons — the happy path ("eligible") is the last line, not buried three ifs deep. This is the "guard clause" pattern, and it's why Python codebases look the way they do.

6.3 Comments and docstrings: explain why, not what#

  • Comments explain why, docstrings explain what. # retry because the API is flaky is a comment; """Fetch a page with retries.""" is a docstring. If a comment restates the code (# increment i), delete it.
  • Docstrings go on modules, classes, public functions — the things someone else calls. One-line summary first, blank line, then details/Args/Returns/Raises as needed (Google or NumPy style; help() and inspect.getdoc render them). Private helpers (_foo) get a comment only if the why is non-obvious.
  • TODO/FIXME/NOTE/HACK prefixes make intent greppable: # TODO: switch to streaming when 03.3 lands. Never leave a bare # fix later.
  • Comment the surprising: workarounds, non-obvious invariants, "this looks wrong but isn't because…". The test: would a competent reader be surprised? Comment that.
python
# docstring_demo.py
import inspect

def chunk_text(text: str, size: int) -> list[str]:
    """Split text into chunks of at most `size` characters.

    Chunks never split a word when avoidable: a word longer than
    `size` is hard-split at `size` (rare, but must not crash).

    Args:
        text: the input text.
        size: maximum characters per chunk; must be >= 1.

    Returns:
        List of chunks in order. Empty input returns [].

    Raises:
        ValueError: if size < 1.
    """
    if size < 1:
        raise ValueError("size must be >= 1")
    chunks: list[str] = []
    current = ""
    for word in text.split():
        if len(word) > size:                       # over-long word: hard-split it
            if current:
                chunks.append(current)
            pieces = [word[i:i + size] for i in range(0, len(word), size)]
            chunks.extend(pieces[:-1])
            current = pieces[-1]                   # the tail may still take more words
            continue
        candidate = f"{current} {word}" if current else word
        if len(candidate) <= size:
            current = candidate
        else:
            chunks.append(current)
            current = word
    if current:
        chunks.append(current)
    return chunks

print(inspect.getdoc(chunk_text).splitlines()[0])
print(chunk_text("the quick brown fox", 10))
print(chunk_text("a supercalifragilistic day", 8))   # the long word is hard-split
print(chunk_text("", 10))
Output4 lines
Split text into chunks of at most `size` characters.
['the quick', 'brown fox']
['a', 'supercal', 'ifragili', 'stic day']
[]

The docstring is a contract, and the three prints check it: normal text splits at word boundaries, the over-long word is hard-split exactly as promised, and empty input returns []. (A docstring that promises behaviour the body doesn't deliver is worse than no docstring — it is a bug report waiting to happen. Treat the "Raises" and "Returns" lines as things a test must prove, which is what Part 7 and 01B.8 are for.)

6.4 ruff: lint and format#

Ruff is the one tool you actually install for Python style — a Rust linter+formatter that replaces flake8, isort, black, pyupgrade and ~50 plugins, at ~100× the speed. As of November 2026 the latest release is 0.17.4 (5 November 2026). You don't need it installed to write good code, but it's the closest thing Python has to gofmt:

bash
uvx ruff check .          # lint: find style bugs and bad patterns
uvx ruff check --fix .    # auto-fix what's safe (unused imports, etc.)
uvx ruff format .         # format: rewrite files to canonical style
uvx ruff check --select ALL .   # every rule (~900), for the curious

Config lives in pyproject.toml — this is the sane default most projects start from:

toml
# pyproject.toml
[tool.ruff]
line-length = 88
target-version = "py313"

[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"]
# E/W pycodestyle, F pyflakes, I isort, UP pyupgrade, B bugbear, SIM simplify, RUF ruff-specific

What the rule families catch that matters here: F (unused imports, undefined names — real bugs), UP (suggests X | Y over Union, list[int] over List), B (mutable default args, useless expressions), SIM (collapsible ifs → your guard clauses), I (import order). ruff format handles whitespace/line-length so you never argue about it in review. VS Code/PyCharm run it on save; CI runs ruff check + ruff format --check.

6.5 Magic numbers, dead code, duplication#

  • Magic numbers: if retries > 3 → MAX_RETRIES = 3 at module top (or Final). If the number has meaning (86400 = seconds/day), name it SECONDS_PER_DAY or compute it. Small numbers in obvious contexts (range(10) in a demo) are fine.
  • Dead code: unused imports (ruff F401), unreachable branches after return, commented-out blocks, functions nothing calls. Delete it — git remembers. # noqa/# type: ignore without a reason is dead-weight pretending to be documentation.
  • Duplication: the rule of three — extract on the third occurrence. The extraction should name the concept (format_ticket_row), not the mechanics (do_csv_thing).

6.6 The Zen of Python#

import this prints Tim Peters' aphorisms — the closest thing Python has to a constitution, and worth reading once:

python
import this
Output · real, deterministic — the module decodes a rot13 string21 lines
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

The ones that map to this lesson: "flat is better than nested" (guard clauses), "explicit is better than implicit" (type hints, keyword args), "readability counts", "there should be one obvious way" (that's why ruff format exists — one format, no bikeshedding).

6.7 Code smells, in one table#

Smell What it looks like The fix
Long function >60 lines, multiple jobs extract by responsibility
Deep nesting 4+ indent levels guard clauses, extract
Boolean flag param send(msg, True) keyword-only arg or enum
Magic number if x > 86400 named constant
God object one class does everything split by responsibility
Shotgun surgery one change touches 8 files the concept is in the wrong place
Dead code unused imports, unreachable branches delete (git remembers)
Comment noise # i += 1 delete; keep only why
Any everywhere hints that say nothing real types at boundaries
Global state module-level mutable dicts pass dependencies in (7)
Premature abstraction helper used once, named vaguely inline it until the third use

6.8 Refactor with proof#

The professional habit: refactor small, prove equivalence. Take the ticket-filtering code from earlier lessons — the ugly version and the clean one produce identical output, verified by assert:

python
# refactor_demo.py
def process_tickets_ugly(tickets):
    res = []
    for i in range(len(tickets)):
        t = tickets[i]
        if t.get("priority") == "URGENT":
            if t.get("status") != "closed":
                res.append(t["id"])
        elif t.get("priority") == "HIGH":
            if t.get("status") != "closed":
                res.append(t["id"])
    return res

def urgent_open_ids(tickets: list[dict]) -> list[str]:
    """Ids of tickets that are urgent/high and still open."""
    return [
        t["id"]
        for t in tickets
        if t["priority"] in ("URGENT", "HIGH")
        and t["status"] != "closed"
    ]

sample = [
    {"id": "a", "priority": "URGENT", "status": "new"},
    {"id": "b", "priority": "HIGH", "status": "closed"},
    {"id": "c", "priority": "LOW", "status": "new"},
    {"id": "d", "priority": "URGENT", "status": "triaged"},
]
assert process_tickets_ugly(sample) == urgent_open_ids(sample) == ["a", "d"]
print("behaviour identical:", urgent_open_ids(sample))
Output1 line
behaviour identical: ['a', 'd']

The clean version is shorter and typed — the comprehension says exactly what it filters. The assert is the safety net: run it before deleting the old code. This is the whole refactoring loop: understand → extract → prove → delete → format (ruff format).


Part 7: Design for change and testing#

Deep-dive

Readable functions are the surface; the architecture underneath determines whether the code survives contact with real requirements. These are the design habits that pay off when the ticket-triage script becomes a service. The "testing" in the part's title means testability: pure functions and passed-in dependencies are what let a test control inputs without mocks. Writing and running the tests themselves is 01B.8.

7.1 Pure functions, I/O at the edges#

The single most useful architectural rule in Python: keep the decision logic pure (no I/O, no globals, no clock, no randomness), and push all I/O to the edges.

python
# edges_demo.py
import json
from pathlib import Path

def classify(text: str) -> str:
    """Pure: same input, same output, no I/O."""
    t = text.lower()
    if "crash" in t or "error" in t:
        return "bug"
    if "invoice" in t or "refund" in t:
        return "billing"
    return "other"

def load_and_classify(path: Path) -> list[dict]:
    """The only function that touches the filesystem."""
    data = json.loads(path.read_text(encoding="utf-8"))
    return [{"subject": item["subject"], "category": classify(item["subject"] + " " + item.get("body", ""))} for item in data]

print(classify("The app crashes on login"))
print(classify("Invoice question"))
print(classify("hello there"))
Output3 lines
bug
billing
other

classify can be unit-tested with plain strings — no temp files, no fixtures, no mocking. load_and_classify is the thin shell that reads, delegates, returns. This is exactly the shape the triage package uses: rules.py is pure, io.py does files, cli.py wires them. The payoff compounds: pure functions are trivially testable (01B.8), parallelisable (01B.4), and safe to cache.

7.2 Small interfaces, dependency passing#

Don't reach for globals — pass dependencies in. The clock, the RNG, the HTTP client, the config: make them parameters so callers (and tests) control them:

python
# deps_demo.py
import random
from datetime import UTC, datetime

def make_report(now: datetime, rng: random.Random) -> dict:
    return {"generated_at": now.isoformat(), "ticket": f"T-{rng.randint(1000, 9999)}"}

fixed = make_report(datetime(2026, 1, 1, tzinfo=UTC), random.Random(42))
print(fixed)
print(make_report(datetime(2026, 1, 1, tzinfo=UTC), random.Random(42)) == fixed)
Output2 lines
{'generated_at': '2026-01-01T00:00:00+00:00', 'ticket': 'T-2824'}
True

Same inputs → same output, every time, because now and rng are arguments. A test passes datetime(2026,1,1) and Random(42) and gets a deterministic report; production passes datetime.now(UTC) and random.Random(). This is dependency injection in its plainest form — no framework needed, and it's why the SDKs take http_client= (4.2). The anti-pattern it replaces: import random + random.randint(...) + datetime.now() buried inside the function, untestable without monkey-patching globals.

Configuration as data follows the same rule — settings are a dataclass/TypedDict built once at startup, passed down, never re-read from the environment deep in the call stack:

python
# config_demo.py
import json
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True, slots=True)
class Config:
    input_path: str = "data/tickets.csv"
    out_dir: str = "reports"
    top_n: int = 3
    verbose: bool = False

def load_config(path: Path | None = None) -> Config:
    if path is None or not path.is_file():
        return Config()
    raw = json.loads(path.read_text(encoding="utf-8"))
    known = {f for f in Config.__dataclass_fields__}
    return Config(**{k: v for k, v in raw.items() if k in known})

print(load_config())
Path("cfg.json").write_text('{"out_dir": "out", "top_n": 5, "unknown": 1}', encoding="utf-8")
print(load_config(Path("cfg.json")))
Output2 lines
Config(input_path='data/tickets.csv', out_dir='reports', top_n=3, verbose=False)
Config(input_path='data/tickets.csv', out_dir='out', top_n=5, verbose=False)

Defaults live in the dataclass; a JSON file overrides them; unknown keys are ignored. Frozen so nothing mutates it mid-run. In production this becomes pydantic-settings reading .env + env vars (01B.2) — same idea, validated.

7.3 Self-documenting code, README, semver, deprecation#

  • Self-documenting code is the goal: good names + small functions + types mean the code is the documentation. Comments and docstrings fill the gaps names can't (the why, the edge cases, the contract).
  • README for anything someone else runs: what it is, how to install/run, the layout, one worked example. The triage package's README in Appendix A is the model — 20 lines, not a novel.
  • Semantic versioning (MAJOR.MINOR.PATCH): bump PATCH for fixes, MINOR for backwards-compatible features, MAJOR for breaking changes. __version__ = "0.1.0" in __init__.py is the convention; tools read it.
  • Deprecation: when you must keep old behaviour, mark it — warnings.deprecated (3.13+) or a docstring note + # TODO: remove in 0.3. Silent removal breaks callers; silent keeping breeds two ways to do everything. The Zen applies: one obvious way.

Part 8: Performance sense for freshers#

Deep-dive

You will not write fast code by guessing — you'll write it by measuring. These are the tools and the intuitions that keep you honest.

8.1 Measure, don't guess#

python
# timing_demo.py
import timeit

setup = "parts = [str(i) for i in range(1000)]"
loop = "s = ''\nfor p in parts:\n    s += p"
join = "s = ''.join(parts)"

t_loop = min(timeit.repeat(loop, setup=setup, number=200, repeat=5))
t_join = min(timeit.repeat(join, setup=setup, number=200, repeat=5))
print(f"loop +=: {t_loop:.4f}s   join: {t_join:.4f}s   ratio: {t_loop/t_join:.1f}x")
Example output · illustrative1 line
loop +=: 0.0119s   join: 0.0015s   ratio: 7.7x
  • timeit runs a snippet many times and reports the best — use it for micro-decisions (which of two ways to build a string). timeit.repeat(..., number=N, repeat=5) + min() filters noise.
  • time.perf_counter() for real elapsed time around a block; time.process_time() for CPU-only. Never time.time() for benchmarking (wall clock includes sleeps).
  • cProfile answers "where does the time actually go":
python
# profile_demo.py
import cProfile, pstats, io

def slow():
    total = 0
    for i in range(200000):
        total += i * i
    return total

def fast():
    return sum(i * i for i in range(200000))

pr = cProfile.Profile()
pr.enable()
slow(); fast()
pr.disable()
s = io.StringIO()
pstats.Stats(pr, stream=s).sort_stats("cumulative").print_stats(6)
print(s.getvalue())
Example output · illustrative6 lines
         200005 function calls in 0.054 seconds
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.042    0.042 profile_demo.py:10(fast)
        1    0.023    0.023    0.042    0.042 {built-in method builtins.sum}
   200001    0.019    0.000    0.019    0.000 profile_demo.py:11(<genexpr>)
        1    0.013    0.013    0.013    0.013 profile_demo.py:4(slow)

Read it: ncalls (how often), tottime (time in the function itself), cumtime (including callees). The fast version spends its time inside sum+genexpr; slow in its own loop. Profile before optimising — the bottleneck is usually not where you think.

8.2 The wins that actually matter#

In order of impact for typical AI-engineering code:

Win Example Why it works
Right data structure set for membership, dict for lookup, deque for queues O(1) vs O(n) — algorithmic, not constant
Don't repeat work compute once, store; functools.cache CPU is finite; I/O is finite; recomputation is waste
Generators for big data for line in file vs readlines() constant memory vs loading everything
join not += "".join(parts) vs loop-append strings are immutable, so += may copy the growing string each time (CPython sometimes optimises this in place, but other implementations and non-local variables don't); join sizes the result once
Avoid premature optimisation don't micro-opt unmeasured code readability first; measure the hot path only
python
# cache_demo.py
import functools

calls = 0

@functools.cache
def classify_once(text: str) -> str:
    global calls
    calls += 1
    return text.split()[0].lower()

print(classify_once("URGENT ticket"))
print(classify_once("URGENT ticket"))
print(classify_once("normal ticket"))
print("real computations:", calls)
print(classify_once.cache_info())
Output5 lines
urgent
urgent
normal
real computations: 2
CacheInfo(hits=1, misses=2, maxsize=None, currsize=2)

@functools.cache memoises by argument — the second "URGENT ticket" call is a dict lookup, not a recompute. cache_info() shows hits/misses. Use it for pure, expensive, repeated calls (embedding lookups, parsed configs, classification of the same text); never for functions with side effects or unhashable args. functools.lru_cache(maxsize=N) bounds memory when the key space is huge.

8.3 The GIL, in one paragraph#

CPython's Global Interpreter Lock allows only one thread to execute Python bytecode at a time — threads help with I/O-bound work (waiting on network/disk releases the GIL) but not CPU-bound work (pure-Python computation holds it). For CPU parallelism use multiprocessing or free-threaded builds (experimental in 3.13, officially supported but still non-default since 3.14 per PEP 779); for I/O concurrency use asyncio — which is exactly why LLM calls (network waits) are async, not threaded. The details are 01B.3 and 01B.4; the takeaway here is: don't add threads to speed up Python computation — they'll fight over the GIL.


Appendix A: the assembled triage package#

This is the support-ticket toolkit every lesson in Module 01A has been building toward — now typed, formatted and documented. Save it as a folder triageproj/ containing triage/ and data/, then run python3 -m triage from inside triageproj/. It needs nothing but the standard library.

A.1 triage/__init__.py#

python
"""Support-ticket triage toolkit.

A small, dependency-free CLI that loads tickets from CSV or JSON,
classifies them with keyword rules, and writes summary reports.
"""

__version__ = "0.1.0"

__all__ = ["__version__"]

A.2 triage/__main__.py#

python
"""Allow `python -m triage` in addition to `python -m triage.cli`."""

from .cli import main

raise SystemExit(main())

A.3 triage/models.py#

python
"""Data model for the triage toolkit.

Everything the rest of the package passes around is one of these types,
so the shapes are declared once, here. The vocabularies follow the data
model 01A.6 built, with one deliberate change: here on Priority a
*lower* number means *more* urgent (01A.6 counted the other way).
"""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum, StrEnum


class Priority(IntEnum):
    """How urgently a ticket needs attention. IntEnum so it sorts and
    compares like a number but prints as a name. Lower = more urgent:
    URGENT is 1, LOW is 4 — the reverse of the 01A.6 toolkit's scale."""

    URGENT = 1
    HIGH = 2
    NORMAL = 3
    LOW = 4


class Status(StrEnum):
    """Where a ticket is in the workflow. StrEnum so JSON and CSV get
    the readable string, not a number or a repr."""

    OPEN = "open"
    IN_PROGRESS = "in_progress"
    RESOLVED = "resolved"
    CLOSED = "closed"


class Category(StrEnum):
    """The kind of problem a ticket describes, decided by rules.py."""

    BUG = "bug"
    BILLING = "billing"
    FEATURE = "feature"
    QUESTION = "question"
    OTHER = "other"


@dataclass(slots=True)
class Ticket:
    """One support ticket: the record 01A.6's toolkit used, plus the
    body/category fields a file-backed CLI needs. Mutable (not frozen)
    so escalate() can move it through the workflow."""

    ticket_id: str
    subject: str
    body: str = ""
    customer: str = "unknown"
    priority: Priority = Priority.NORMAL
    status: Status = Status.OPEN
    category: Category = Category.OTHER
    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}] "
            f"{self.status.value}: {self.subject} ({self.customer})"
        )

A.4 triage/rules.py#

python
"""Keyword rules that classify a ticket's text.

Deliberately simple: this is a teaching example, not a real classifier.
Each rule is (category, keywords); the category with the most keyword
hits wins. No AI, no network — just string matching.
"""

from __future__ import annotations

from .models import Category, Priority

# Order matters only for ties: earlier categories win equal scores.
_RULES: tuple[tuple[Category, tuple[str, ...]], ...] = (
    (Category.BUG, ("crash", "error", "broken", "fail", "bug", "exception", "500")),
    (Category.BILLING, ("invoice", "charge", "refund", "billing", "payment", "receipt")),
    (Category.FEATURE, ("feature", "request", "add support", "would be nice", "enhancement")),
    (Category.QUESTION, ("how do", "how to", "question", "help", "where is")),
)


def classify_ticket(subject: str, body: str) -> Category:
    """Return the Category whose keywords appear most in the text.

    Ties resolve to the earlier rule in _RULES, so BUG beats BILLING
    when a ticket mentions both equally.
    """
    text = f"{subject} {body}".lower()
    best_category = Category.OTHER
    best_score = 0
    for category, keywords in _RULES:
        score = sum(text.count(keyword) for keyword in keywords)
        if score > best_score:
            best_category, best_score = category, score
    return best_category


def suggest_priority(subject: str, body: str) -> Priority:
    """A rough priority guess from urgency words. Deliberately crude:
    a human still reviews every suggestion."""
    text = f"{subject} {body}".lower()
    if any(word in text for word in ("down", "outage", "urgent", "asap", "production")):
        return Priority.URGENT
    if any(word in text for word in ("critical", "blocking", "cannot", "won't", "wont")):
        return Priority.HIGH
    if any(word in text for word in ("minor", "cosmetic", "low", "when you can")):
        return Priority.LOW
    return Priority.NORMAL

A.5 triage/io.py#

python
"""Loading tickets from CSV and JSON, and writing reports back out.

Every loader returns a (tickets, problems) pair: good rows become
Ticket objects, bad rows become human-readable problem strings. The
CLI prints the problems and continues — one bad row never sinks a run.
"""

from __future__ import annotations

import csv
import json
import logging
from dataclasses import asdict
from pathlib import Path
from typing import Any

from .models import Priority, Status, Ticket
from .rules import classify_ticket, suggest_priority

log = logging.getLogger(__name__)

CSV_FIELDS = ("id", "subject", "body", "customer", "priority", "status", "tags", "notes")
REPORT_CSV_FIELDS = (*CSV_FIELDS, "category")


def _parse_list(raw: str) -> list[str]:
    """CSV has no list type: values arrive as 'a;b;c' or 'a, b, c'."""
    return [tag.strip() for tag in raw.replace(";", ",").split(",") if tag.strip()]


def _row_to_ticket(row: dict[str, str]) -> Ticket:
    """Turn one CSV row into a Ticket, classifying as we go.

    Raises ValueError on anything a human should look at; the loader
    catches it per row so one bad line doesn't lose the file.
    """
    ticket_id = row.get("id", "").strip()
    subject = row.get("subject", "").strip()
    if not ticket_id or not subject:
        raise ValueError("missing id or subject")

    priority_name = row.get("priority", "").strip().upper() or "NORMAL"
    try:
        priority = Priority[priority_name]
    except KeyError:
        raise ValueError(f"unknown priority {row.get('priority')!r}") from None
    status_name = row.get("status", "").strip().lower() or "open"
    try:
        status = Status(status_name)
    except ValueError:
        raise ValueError(f"unknown status {row.get('status')!r}") from None

    category = classify_ticket(subject, row.get("body", ""))
    if priority is Priority.NORMAL:
        priority = suggest_priority(subject, row.get("body", ""))
    return Ticket(
        ticket_id=ticket_id,
        subject=subject,
        body=row.get("body", "").strip(),
        customer=row.get("customer", "").strip() or "unknown",
        priority=priority,
        status=status,
        category=category,
        tags=_parse_list(row.get("tags", "")),
        notes=_parse_list(row.get("notes", "")),
    )


def load_tickets_csv(path: Path) -> tuple[list[Ticket], list[str]]:
    """Read tickets.csv. Returns (tickets, problems); problems lists
    'line N: reason' for every skipped row."""
    tickets: list[Ticket] = []
    problems: list[str] = []
    with path.open(newline="", encoding="utf-8") as fh:
        for lineno, row in enumerate(csv.DictReader(fh), start=2):
            try:
                tickets.append(_row_to_ticket(row))
            except ValueError as exc:
                problems.append(f"line {lineno}: {exc}")
                log.warning("skipping row %d: %s", lineno, exc)
    return tickets, problems


def load_tickets_json(path: Path) -> tuple[list[Ticket], list[str]]:
    """Read a JSON file holding a list of ticket objects."""
    tickets: list[Ticket] = []
    problems: list[str] = []
    data: Any = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, list):
        raise ValueError(f"{path} must contain a JSON list of tickets")
    for index, item in enumerate(data, start=1):
        try:
            tickets.append(_row_to_ticket(_json_item_to_row(item)))
        except (ValueError, AttributeError, TypeError) as exc:
            problems.append(f"item {index}: {exc}")
            log.warning("skipping item %d: %s", index, exc)
    return tickets, problems


def _json_item_to_row(item: Any) -> dict[str, str]:
    """Adapt a JSON ticket (tags/notes may already be lists) to the CSV
    row shape _row_to_ticket understands."""
    if not isinstance(item, dict):
        raise TypeError("ticket is not an object")
    row = {key: str(item.get(key, "")) for key in CSV_FIELDS if key not in ("tags", "notes")}
    for list_key in ("tags", "notes"):
        value = item.get(list_key, "")
        row[list_key] = ";".join(value) if isinstance(value, list) else str(value)
    return row


def load_tickets(path: Path) -> tuple[list[Ticket], list[str]]:
    """Pick a loader by file extension."""
    if path.suffix == ".json":
        return load_tickets_json(path)
    if path.suffix == ".csv":
        return load_tickets_csv(path)
    raise ValueError(f"unsupported file type: {path.suffix or '(none)'}")


def write_text_atomic(path: Path, text: str) -> None:
    """Write via a temp file + replace, so a crash mid-write can't leave
    a half-written report behind."""
    tmp = path.with_name(path.name + ".tmp")
    tmp.write_text(text, encoding="utf-8")
    tmp.replace(path)


def save_report_json(path: Path, report: dict[str, Any]) -> None:
    write_text_atomic(path, json.dumps(report, indent=2, ensure_ascii=False) + "\n")


def save_report_csv(path: Path, tickets: list[Ticket]) -> None:
    """One row per ticket, with the classified fields filled in."""
    with path.open("w", newline="", encoding="utf-8") as fh:
        writer = csv.DictWriter(fh, fieldnames=REPORT_CSV_FIELDS)
        writer.writeheader()
        for t in tickets:
            writer.writerow(
                {
                    "id": t.ticket_id,
                    "subject": t.subject,
                    "body": t.body,
                    "customer": t.customer,
                    "priority": t.priority.name,
                    "status": t.status.value,
                    "tags": ";".join(t.tags),
                    "notes": ";".join(t.notes),
                    "category": t.category.value,
                }
            )


def tickets_to_jsonable(tickets: list[Ticket]) -> list[dict[str, Any]]:
    """asdict() gives plain dicts; enums become their values for JSON."""
    out = []
    for t in tickets:
        row = asdict(t)
        row["priority"] = t.priority.name
        row["status"] = t.status.value
        row["category"] = t.category.value
        out.append(row)
    return out

A.6 triage/report.py#

python
"""Summarise a list of tickets into counts a human can scan."""

from __future__ import annotations

from collections import Counter
from dataclasses import dataclass
from typing import Any

from .models import Priority, Status, Ticket


@dataclass(frozen=True, slots=True)
class Summary:
    """The report: totals plus per-dimension breakdowns."""

    total: int
    by_status: dict[str, int]
    by_category: dict[str, int]
    by_priority: dict[str, int]
    urgent_open: int
    top_categories: tuple[tuple[str, int], ...] = ()
    urgent_examples: tuple[str, ...] = ()

    def to_dict(self) -> dict[str, Any]:
        return {
            "total": self.total,
            "by_status": self.by_status,
            "by_category": self.by_category,
            "by_priority": self.by_priority,
            "urgent_open": self.urgent_open,
            "top_categories": dict(self.top_categories),
            "urgent_examples": list(self.urgent_examples),
        }


def summarise(tickets: list[Ticket], top_n: int = 3) -> Summary:
    """Count tickets by status, category and priority.

    'urgent_open' counts HIGH or URGENT tickets that aren't resolved or
    closed — the number a triage lead actually wants first.
    'urgent_examples' holds summary lines for up to three of them.
    """
    by_status = Counter(t.status.value for t in tickets)
    by_category = Counter(t.category.value for t in tickets)
    by_priority = Counter(t.priority.name for t in tickets)
    urgent = [
        t
        for t in tickets
        if t.priority in (Priority.HIGH, Priority.URGENT)
        and t.status not in (Status.RESOLVED, Status.CLOSED)
    ]
    top = tuple(by_category.most_common(top_n))
    return Summary(
        total=len(tickets),
        by_status=dict(sorted(by_status.items())),
        by_category=dict(sorted(by_category.items())),
        by_priority=dict(sorted(by_priority.items())),
        urgent_open=len(urgent),
        top_categories=top,
        urgent_examples=tuple(t.summary_line() for t in urgent[:3]),
    )

A.7 triage/cli.py#

python
"""Command-line interface: python -m triage [options]."""

from __future__ import annotations

import argparse
import logging
import sys
from pathlib import Path

from .io import load_tickets, save_report_csv, save_report_json, tickets_to_jsonable
from .report import summarise

log = logging.getLogger(__name__)


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="triage",
        description="Classify support tickets and write summary reports.",
    )
    parser.add_argument(
        "--input",
        type=Path,
        default=Path("data/tickets.csv"),
        help="tickets file (.csv or .json); default: data/tickets.csv",
    )
    parser.add_argument(
        "--outdir",
        type=Path,
        default=Path("reports"),
        help="where to write report.json and report.csv; default: reports/",
    )
    parser.add_argument(
        "--top",
        type=int,
        default=3,
        metavar="N",
        help="how many top categories to print; default: 3",
    )
    parser.add_argument(
        "--verbose", "-v", action="store_true", help="log every skipped row"
    )
    return parser


def main(argv: list[str] | None = None) -> int:
    args = build_parser().parse_args(argv)
    logging.basicConfig(
        level=logging.DEBUG if args.verbose else logging.WARNING,
        format="%(levelname)s %(name)s: %(message)s",
    )

    if not args.input.is_file():
        print(f"error: input file not found: {args.input}", file=sys.stderr)
        return 2

    try:
        tickets, problems = load_tickets(args.input)
    except (OSError, ValueError) as exc:
        print(f"error: {exc}", file=sys.stderr)
        return 2

    if not tickets:
        print("error: no readable tickets", file=sys.stderr)
        return 1

    summary = summarise(tickets, top_n=args.top)
    args.outdir.mkdir(parents=True, exist_ok=True)
    save_report_json(args.outdir / "report.json", summary.to_dict() | {"tickets": tickets_to_jsonable(tickets)})
    save_report_csv(args.outdir / "report.csv", tickets)

    # Console summary: the numbers a triage lead reads first.
    print(f"Loaded {summary.total} tickets from {args.input}")
    if problems:
        print(f"Skipped {len(problems)} bad rows:")
        for problem in problems:
            print(f"  - {problem}")
    print(f"Urgent or high, still open: {summary.urgent_open}")
    for line in summary.urgent_examples:
        print(f"  {line}")
    print("By status:")
    for status, count in summary.by_status.items():
        print(f"  {status:<12} {count}")
    print("By category:")
    for category, count in summary.by_category.items():
        print(f"  {category:<10} {count}")
    print(f"Wrote {args.outdir / 'report.json'} and {args.outdir / 'report.csv'}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

A.8 data/tickets.csv and data/tickets.json#

csv
id,subject,body,customer,priority,status,tags,notes
T-1001,App crashes on login,"The mobile app crashes with a 500 error every time I log in",acme,URGENT,open,android;crash,
T-1002,Invoice question,"I have a question about my invoice from last month",globex,NORMAL,open,billing,
T-1003,Feature request,"It would be nice if the export supported CSV. Feature request for Q1",initech,NORMAL,open,export,
T-1004,Password reset broken,"Password reset emails never arrive. This is blocking our whole team",umbrella,HIGH,in_progress,auth,
T-1005,How do I add seats?,"How do I add more seats to our plan?",wayne,LOW,open,billing,
T-1006,Chart looks wrong on dark mode,"The dashboard chart renders incorrectly in dark mode, minor cosmetic issue",stark,LOW,open,ui,
T-1007,API returns 500 on /v1/search,"Our integration gets exception errors and HTTP 500 from /v1/search since Tuesday",oscorp,URGENT,in_progress,api,
T-1008,Refund for cancelled plan,"Please process a refund for the cancelled annual plan",acme,NORMAL,resolved,billing,
T-1009,Suggestion: dark mode for reports,"Enhancement request: add a dark mode option to PDF reports",globex,NORMAL,open,reports,
T-1010,Where is the audit log?,"Where is the audit log export in the settings page?",initech,LOW,closed,question,
T-1011,Broken webhook retries,"Webhook delivery fails and retries forever; error in payload",umbrella,HIGH,open,api,
T-1012,,Missing subject row should be skipped,,,open,,
json
[
  {"id": "J-2001", "subject": "Login loop after update", "body": "App crashes on login since the update", "customer": "initech", "priority": "HIGH", "status": "open", "tags": ["ios", "crash"], "notes": []},
  {"id": "J-2002", "subject": "Double charge on invoice", "body": "I see two charges for the same invoice", "customer": "acme", "priority": "URGENT", "status": "open", "tags": ["billing"], "notes": ["customer on pro plan"]},
  {"id": "J-2003", "subject": "", "body": "no subject here", "customer": "globex", "priority": "LOW", "status": "open"}
]

A.9 README.md#

text
# triage — support-ticket triage toolkit

A small, dependency-free Python package that loads support tickets from
CSV or JSON, classifies them with keyword rules, and writes summary
reports. It is the running example of Module 01A: the data model and
vocabularies follow the ones 01A.6 built (the `Status` values and the
`ticket_id`/`customer`/`tags`/`notes` fields; only the `Priority`
direction is reversed), and this listing is the consolidated final form — earlier lessons each
shipped a smaller iteration of the same toolkit.

## Layout

triageproj/
├── data/
│   ├── tickets.csv        # sample input (one deliberately bad row)
│   └── tickets.json       # the same pipeline, JSON loader (one bad item)
├── triage/
│   ├── __init__.py        # package marker + version
│   ├── __main__.py        # makes `python -m triage` work
│   ├── models.py          # Ticket dataclass, Priority/Status/Category enums
│   ├── rules.py           # keyword classifier + priority suggester
│   ├── io.py              # CSV/JSON loaders, report writers (atomic)
│   ├── report.py          # Counter-based summary
│   └── cli.py             # argparse entry point
└── README.md

## Run it

From this directory (the folder that contains `triage/` and `data/`):

    python3 -m triage                      # reads data/tickets.csv, writes reports/
    python3 -m triage --input data/tickets.csv --outdir reports
    python3 -m triage --top 5 -v           # verbose: log every skipped row

The default input path is relative to your current directory, not to
the package — `cd` into this folder first, or pass an explicit path.

## What it demonstrates

- `dataclass` records and `IntEnum`/`StrEnum` vocabularies based on
  01A.6's data model (`Priority.URGENT == 1` — lower means more urgent,
  the reverse of 01A.6)
- CSV and JSON I/O with `encoding="utf-8"`, per-row error collection
- Atomic report writes (temp file + `replace`)
- Type hints on every public function, written with strict checkers in
  mind — run `uvx mypy --strict triage/` and `uvx ruff check triage/` to
  see where your checker lands and fix whatever it reports
- `Counter` summaries, `argparse` CLI, `logging`

A.10 Running it — real output#

bash
$ cd triageproj
$ python3 -m triage
WARNING triage.io: skipping row 13: missing id or subject
Loaded 11 tickets from data/tickets.csv
Skipped 1 bad rows:
  - line 13: missing id or subject
Urgent or high, still open: 4
  T-1001 [URGENT] open: App crashes on login (acme)
  T-1004 [HIGH] in_progress: Password reset broken (umbrella)
  T-1007 [URGENT] in_progress: API returns 500 on /v1/search (oscorp)
By status:
  closed       1
  in_progress  2
  open         7
  resolved     1
By category:
  billing    2
  bug        4
  feature    2
  other      1
  question   2
Wrote reports/report.json and reports/report.csv

The WARNING line comes from logging in io.py (one bad row, skipped, run continues); the summary comes from Counter in report.py; the files are written atomically. python3 -m triage --input data/tickets.json --outdir reports-json works identically on the JSON file (2 tickets loaded, 1 skipped).


Appendix B: are you ready for 01B?#

A self-check — answer honestly, no peeking:

  1. Write the annotation for "a function taking a list of ticket dicts and returning the count of urgent ones". Now write it so it accepts any sequence, not just list.
  2. def f(x: int | None = None) -> int: — what does x | None mean here, and what would Optional[int] be?
  3. Why does isinstance(x, list[int]) fail while isinstance(x, list) works?
  4. You have JSON from an API: {"id": "T-1", "priority": "HIGH", "tags": ["a","b"]}. Choose TypedDict, NamedTuple, or dataclass — justify.
  5. class Movie(TypedDict): title: str — is Movie() valid? Is Movie(title=1) valid at run time? What catches the wrong type?
  6. What's the difference between Any and object as a parameter type?
  7. Write def first[T](xs: list[T]) -> T in the pre-3.12 spelling.
  8. When do you need from __future__ import annotations or quotes — and why is it unnecessary on 3.14?
  9. cast(int, "5") — what does it do at run time? When is it the right tool?
  10. assert_never(x) — what does it signal to a checker, and what happens if it's reached?
  11. Your function reads a file and parses it and classifies. Split it into pure + I/O parts — name them.
  12. datetime.now() inside a function makes it untestable — what's the fix?
  13. s += part in a loop over 10k strings vs "".join(parts) — which wins and why?
  14. ruff check --fix changed your import order — which rule family did that, and should you fight it?
  15. python3 -m triage fails with ModuleNotFoundError: No module named 'triage' — what's the likely cause?
Answers
  1. def count_urgent(tickets: Sequence[dict[str, Any]]) -> int: — Sequence from collections.abc accepts list, tuple, range…
  2. int | None = "int or None" (the modern Optional[int]); default None makes the arg optional.
  3. list[int] is a parameterized generic — isinstance can't check parameters at run time. Bare list works.
  4. TypedDict — it already is the JSON dict shape; no conversion needed. (A dataclass would force Model(**data) + asdict() round-trips.)
  5. Movie() fails (missing required key title) only for checkers — at run time Movie(title=1) builds {'title': 1} happily; a static checker or Pydantic catches it.
  6. Any = unchecked both ways; object = must narrow before use. Prefer object for honesty.
  7. T = TypeVar("T") then def first(xs: list[T]) -> T:.
  8. On ≤3.13, annotations evaluate at def time so forward references need quotes/__future__; on 3.14 PEP 649 makes them lazy — unnecessary.
  9. Returns "5" unchanged — it's a checker hint, not a conversion. Use when the checker can't see what you know; never as validation.
  10. "This branch is unreachable — x should be Never". At run time it raises AssertionError.
  11. e.g. parse_ticket(text) -> Ticket (pure) + load_and_parse(path) -> list[Ticket] (I/O).
  12. Pass now: datetime as a parameter; caller supplies datetime.now(UTC) or a fixed value in tests.
  13. join — += can copy the growing string on each iteration (worst case O(n²); CPython sometimes optimises this in place, but you shouldn't rely on it), while join computes the size once and allocates once.
  14. The I (isort) rules — don't fight; canonical import order keeps diffs clean.
  15. You're not in triageproj/ — python -m resolves packages from the current directory (or PYTHONPATH), not from the script's location.

Four mistakes that account for most typing/readability bugs in real codebases — each with real output:

python
# mistakes_gallery.py
from typing import Any

# 1. "Type hints validate" -> silently wrong result
def line_total(price: float, quantity: int) -> float:
    return price * quantity

print("hint-as-validation:", line_total("9.99", 3))

# 2. "Any everywhere" -> bug hides behind the escape hatch
def parse_label(value: Any) -> str:
    return value.strip().upper()

try:
    parse_label(42)
except AttributeError as exc:
    print("any-hides-bug:", exc)

# 3. "x | None means optional arg" -> still a required argument
def greet(name: str | None) -> str:
    return f"hi {name}"

try:
    greet()
except TypeError as exc:
    print("none-not-optional:", exc)

# 4. comment noise: the code already says it
def f(user):
    # check if user is None
    if user is None:
        # return the string "none"
        return "none"
    # return the user's name
    return user.name

print("comment-noise:", f(None))
Output4 lines
hint-as-validation: 9.999.999.99
any-hides-bug: 'int' object has no attribute 'strip'
none-not-optional: greet() missing 1 required positional argument: 'name'
comment-noise: none
  1. Hints treated as validation — "9.99" * 3 repeats the string; no error, wrong answer. Hints describe; checkers/Pydantic enforce (1.2, 5.4).
  2. Any everywhere — parse_label(42) fails deep inside .strip(), not at the boundary where the wrong type entered. Any is for JSON edges and stubs, not your own functions (2.3).
  3. X | None confusion — str | None means "str or None", not "argument optional"; greet() still fails because the parameter has no default. Optional argument = = None default; nullable value = | None.
  4. Comment noise and over-engineering — # check if user is None restates the if; delete it. The over-engineering twin: a TicketProcessorFactory for three tickets — two similar lines are fine, the third copy is the refactor signal (6.2, 6.5).

Common misconceptions#

Misconception Reality
"Type hints enforce types at run time." They don't — x: int = "five" runs fine. Checkers and Pydantic enforce; hints describe.
"X | None means the key/arg is optional." It means the value may be None — the key/arg is still required (nullable ≠ omittable).
"Optional/Union/List are the modern spellings." Legacy — read them in old code/SDKs, write X | Y, X | None, list[int].
"isinstance(x, list[int]) works." TypeError — parameterized generics can't be isinstance targets; use list or collections.abc.
"Any is safer than no annotation." It's a hole — worse than object, which at least forces narrowing.
"TypedDict validates like Pydantic." It's a plain dict at run time — Movie(title=1) succeeds. Validation is the checker's or Pydantic's job.
"cast converts the value." It's the identity function — a lie told to the checker, nothing more.
"Final makes a value immutable." It means "don't reassign the name" — a Final list still mutates.
"assert_type/assert_never check at run time." assert_type is a checker probe; assert_never raises AssertionError only because it's meant to be unreachable.
"A Protocol needs inheritance." Structural — anything with the methods fits; @runtime_checkable enables isinstance.
"type X = int makes a new type." It's an alias — X and int are interchangeable (unlike NewType).
"mypy strict is the default you should enable day one." It's a ratchet — start with signatures, add flags gradually, # type: ignore[code] at true boundaries.
"Hints cost performance." Lazy objects, evaluated on demand — nanoseconds at def time, nothing per call.
"s += x in a loop is fine." Strings are immutable, so += may copy the growing string on every pass (CPython sometimes optimises it, other runtimes don't); join is the idiom and the clear winner on large inputs.
"Threads speed up Python compute." The GIL serialises bytecode — threads help I/O waits, not CPU work; use asyncio/processes.

Key takeaways#

  • Hints are promises, not enforcement — x: int = "five" runs; only checkers/Pydantic reject it. Gradual typing: annotate what you can, Any at true boundaries.
  • The vocabulary: built-in generics (list[int]), unions (X | Y, X | None), Callable, collections.abc interfaces, Literal, Final, NewType, type aliases (3.12+).
  • Shapes: TypedDict for JSON dicts (still plain dicts), NamedTuple for tiny records, dataclass for domain objects, Protocol for "anything with these methods", generics via TypeVar/Generic or 3.12 brackets.
  • Self, Annotated, cast, assert_type, assert_never, @overload, @override, NoReturn, reveal_type, TypeIs/TypeGuard (your own narrowing functions, 3.7), TYPE_CHECKING, forward references — the tools for real-world signatures; get_type_hints resolves them, inspect.signature displays them.
  • Read SDK signatures fast: keyword-only *, X | Y | None | NotGiven unions, Mapping/Callable/Unpack/httpx2 types, TYPE_CHECKING + cached_property lazy imports.
  • Checkers: mypy 2.4.1 and pyright 1.1.414 are the safe defaults; ty 0.0.101 (beta) and pyrefly 1.4.1 are the fast new generation; run via uvx, configure in pyproject.toml, adopt strictness gradually.
  • Readable code: PEP 8 via ruff (0.17.4), names that answer questions, guard clauses over nesting, comments explain why, docstrings on public API, magic numbers named, dead code deleted.
  • Design: pure functions at the core, I/O at the edges, dependencies passed in, config as frozen data, no global state.
  • Performance: measure with timeit/perf_counter/cProfile; the wins are right data structures, no repeated work, generators, join, functools.cache — not micro-optimisation. The GIL means threads ≠ CPU speedup.
  • The package: triage/ is the Module 01A capstone — typed, formatted, documented, runnable.

Where you'll use this in the AI path#

Skill from this lesson Used in
Reading SDK signatures (X | Y, Callable, NotGiven, Unpack) 03.1 The Provider APIs and every SDK call in Module 03
TypedDict/Pydantic models as schemas 03.4 Structured Output and 01B.6
Protocol for provider/store interfaces 03.11 provider-agnostic client and 06 embeddings/vector stores
Generics (list[T] -> T, Self) SDK response types, ToolRegistry in 08A.6, batch helpers in 03.9
Type hints → JSON Schema for tools 08A.6 Designing Tools and 03.5 Tool Calling
ruff + clean code habits every later module's samples; 01B.1 project setup configures it
Pure functions / dependency passing / config 01B.8 pytest fixtures, 03.10 testing LLM code, 11A.x production
timeit/cProfile/functools.cache 06.2 embedding pipelines, 11B.3 caching, 05.x ingestion

Terms introduced in this lesson#

Term One-line definition
Type hint / annotation An expression attached to a name declaring its type; stored, not enforced
__annotations__ The dict holding a function/module/class's annotations
inspect.signature Reconstructs a callable's full signature including annotations
get_type_hints Resolves string/lazy annotations to real type objects
Gradual typing Type checking that coexists with dynamic code; hints are optional per-symbol
types.GenericAlias The runtime object list[int] produces; get_origin/get_args inspect it
Union (X | Y) "One of these types"; X | None = optional value
Optional / Union Legacy spellings of X | None / X | Y — read, don't write
Any The unchecked escape hatch — disables checking in both directions
object "Some object" — forces narrowing before use; safer than Any
Callable[[A], R] A function type: args list → return type
collections.abc interfaces Iterable, Iterator, Sequence, Mapping, Callable — behaviour contracts for isinstance
Literal[...] Exactly these values — string/int enums without Enum
Final "Assign once" — advisory, doesn't freeze the object
NewType A distinct type alias for checkers; identity at run time
Type alias / type statement Name for a complex type; type X = ... (3.12+) makes a TypeAliasType
TypedDict A dict with declared keys/types; still a plain dict at run time
Required / NotRequired Per-key optional overrides inside TypedDict (3.11+)
ReadOnly TypedDict key checkers won't let you assign (3.13+)
NamedTuple Immutable tuple with named fields and helpers
Protocol Structural typing contract — satisfied by shape, not inheritance
@runtime_checkable Enables isinstance on a Protocol (presence only)
TypeVar / Generic Classic generics spelling; T links input and output types
PEP 695 syntax def f[T] / class C[T] bracket generics — 3.12+
Self "This same class" return/parameter type (3.11+)
Annotated[T, ...] Type plus arbitrary metadata for tools (Pydantic, FastAPI)
cast Identity function that asserts a type to the checker
assert_type Returns value; makes the checker verify the inferred type
assert_never "Unreachable" marker — raises AssertionError, satisfies Never
TYPE_CHECKING True for checkers, False at run time — import-only-for-typing idiom
Forward reference An annotation naming a not-yet-defined type; lazy on 3.14
TypeGuard / TypeIs Return-type markers for user-defined type predicates; TypeIs (3.13+) narrows both branches
TypeForm Marks a parameter as accepting a type expression (3.15, PEP 747); identity at run time
@overload Declares several call signatures with different return types for one function; checker-only
@override Marks a method as intentionally replacing a parent's, so a checker can catch a stale override (3.12+)
NoReturn / Never Return type of a function that never returns normally; code after it is unreachable
reveal_type Asks the checker to print the type it infers for an expression; prints Runtime type is ... at run time
py.typed / types-* stubs The marker that says a package ships hints, and the stub-only packages for libraries that don't
NotGiven sentinel SDK pattern: "argument omitted" ≠ None
Unpack[TypedDict] Types the keys of **kwargs (PEP 692)
Static type checker mypy/pyright/ty/pyrefly — reads hints without running code
Strictness ratchet Gradual adoption: signatures first, flags one at a time
Guard clause Early return/raise that flattens nesting
Code smell A surface pattern suggesting deeper design trouble
Pure function No I/O, no globals, no clock/RNG — same input, same output
Dependency injection Passing collaborators (clock, client, config) as arguments
functools.cache Memoise a pure function's results by argument
GIL Global Interpreter Lock — serialises bytecode; threads ≠ CPU parallelism

All terms are also collected in the glossary.


Exercises#

Type, refactor, decode. Solutions inside <details>; outputs were run for real where deterministic.

  1. Annotate def total_price(items): ... so it takes list[dict[str, float]] and returns float. Then widen the input to Sequence.
  2. Predict what print(isinstance([], collections.abc.Sequence)) and print(isinstance([], list[int])) do — run both.
  3. Rewrite def find(user_id): return user.get(user_id) if user_id in user else None with proper hints, using X | None.
  4. TypedDict: (from typing import ReadOnly, TypedDict, Python 3.13+) define class Usage(TypedDict) with prompt_tokens: int, completion_tokens: int, total_tokens: ReadOnly[int] — explain why total_tokens is ReadOnly.
  5. Choose: for {"lat": 1.2, "lon": 45.6} pick TypedDict, NamedTuple, or dataclass — justify in two sentences.
  6. Generics: write def middle[T](xs: list[T]) -> T (3.12+) and the TypeVar spelling.
  7. Protocol: write a Closable Protocol with def close(self) -> None, make a class satisfy it without inheriting, prove isinstance works with @runtime_checkable.
  8. Decode: annotate def send(self, *, text: str, max_tokens: int = 1000, stream: bool = False) -> Response: — which params are keyword-only? What does -> Response promise?
  9. Forward refs: explain why def f(x: Later) -> Later works on 3.14 but fails on 3.11 — and the two fixes for 3.11.
  10. Refactor: take a nested if version of "find first ticket with priority URGENT and status NEW" and rewrite with a guard-clause/comprehension; prove identical output with assert on a sample.
  11. Ruff: run uvx ruff check --select F,I,UP,B,SIM --target-version py313 (the UP rules only modernise syntax your target version supports) on a file with from typing import List, Optional, Union and unused imports — predict then verify the fixes.
  12. Performance: time "".join([str(i) for i in range(10000)]) vs a += loop with timeit — report the ratio (label your numbers Example output (illustrative — your exact output will differ):, since they depend on your machine and Python build).
  13. Config: convert three os.environ.get(...) calls scattered through a script into a frozen Config dataclass loaded once — show before/after.
  14. Any audit: find every Any in a sample function signature; for each, decide "real type" vs "genuine boundary" — rewrite the real ones.
  15. Build: assemble the triage package from Appendix A, run python3 -m triage, and confirm it reports Loaded 11 tickets and Skipped 1 bad rows. Then append a row to data/tickets.csv with a non-empty subject but an unknown priority — e.g. T-1013,Slow nightly export,The export takes forever,globex,MEH,open,, — and verify the skipped-row count goes from 1 to 2 with a new line 14: unknown priority 'MEH' problem.
Solutions
  1. def total_price(items: list[dict[str, float]]) -> float: then Sequence[dict[str, float]] from collections.abc.
  2. isinstance([], collections.abc.Sequence) → True; isinstance([], list[int]) → TypeError: isinstance() argument 2 cannot be a parameterized generic.
  3. def find(user: dict[int, str], user_id: int) -> str | None: with return user.get(user_id) (or user[user_id] if user_id in user else None).
  4. total_tokens is derived from the other two — ReadOnly tells checkers "don't assign it"; it documents a computed field.
  5. NamedTuple — two numeric fields, immutable, unpackable, no behaviour needed. dataclass if methods/mutation needed; TypedDict only if it must stay a dict.
  6. def middle[T](xs: list[T]) -> T: return xs[len(xs)//2] and T = TypeVar("T"); def middle(xs: list[T]) -> T: ....
  7. class Closable(Protocol): def close(self) -> None: ... + @runtime_checkable; a class with def close(self): ... passes isinstance.
  8. All params after * are keyword-only — text, max_tokens, stream all must be named. -> Response promises a Response object back.
  9. 3.11 evaluates annotations at def time → NameError. Fixes: quote "Later" or from __future__ import annotations.
  10. [t["id"] for t in tickets if t["priority"] == "URGENT" and t["status"] == "NEW"] — assert against the loop version on sample data.
  11. With --fix, List→list, Optional[X]→X | None, Union[X,Y]→X | Y, unused imports removed and imports sorted (the F, UP and I families); B and SIM only report. Without --fix ruff just lists the findings.
  12. join is typically several times faster, but the ratio depends on your Python build and string sizes — CPython sometimes optimises += in place, so don't expect the same number as anyone else. Use min(timeit.repeat(..., number=N, repeat=5)) as in 8.1 and report your own figures.
  13. @dataclass(frozen=True) class Config: api_key: str; model: str; timeout: float loaded once in main, passed down.
  14. e.g. def parse(payload: dict[str, Any]) -> Ticket: — Any is honest at the JSON boundary; def add(a: int, b: int) should never be Any.
  15. Baseline run prints Loaded 11 tickets from data/tickets.csv and Skipped 1 bad rows: with - line 13: missing id or subject. After appending the MEH-priority row, Skipped 2 bad rows: appears plus a new - line 14: unknown priority 'MEH' line — _row_to_ticket raises ValueError per bad row and load_tickets_csv collects it into problems. (Rows with an empty id/subject are rejected by the earlier missing id or subject guard before classification runs, and classify_ticket already returns Category.OTHER when no keyword scores — so no change to classify_ticket can move the skip count; the bad-row path lives in _row_to_ticket.)

Check yourself#

  1. What does x: int = "five" do at run time, and what does enforce the type?
  2. Name three places annotations are stored/read besides source code.
  3. list[int] vs typing.List[int] — which to write, and why does the other still exist?
  4. def f(x: int | None) vs def f(x: Optional[int]) — same thing?
  5. Why can't you write isinstance(x, list[int])?
  6. Any vs object — which is "safer" and why?
  7. class Movie(TypedDict): title: str; year: int — is year required? Is title: str | None required?
  8. total=False vs NotRequired — difference?
  9. NamedTuple vs dataclass — pick one for a (lat, lon) pair and justify.
  10. What does @runtime_checkable enable, and what does it not check?
  11. def first[T](xs: list[T]) -> T — what Python version, and what's the older spelling?
  12. cast(int, "5") at run time — what happens? When is cast appropriate?
  13. if TYPE_CHECKING: — when is it True, and why does get_type_hints fail on such imports?
  14. In OpenAI.__init__, what does | NotGiven in a union mean?
  15. List the four checkers and one reason to pick each.

Further resources#


← 01A.9 — Files, Paths, JSON and CSV | Module 01A overview | 01A.11 — Coming from PHP, JavaScript or Java: Side by Side →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close