Code design: readable code, abstractions, review, library design

Reading: 42 min, plus 17 in closed details. How to shape Python so the next change is cheap and safe: cohesion and coupling, deep modules and information hiding, interfaces and dependency direction, composition over inheritance, functional core and imperative shell, error design, readable names, refactoring in small tested steps, patterns, code an LLM agent can change safely, technical debt, library design and review. One real handler is refactored in ten measured steps (2026-10-04). Child page of Topic: swe-and-system-design. Data as of October 2026.

The idea in one screen

Good code design keeps the next change cheap and safe: put what changes together behind a small interface that hides a lot (high cohesion, low coupling, deep modules), let dependencies point toward the stable rules and keep I/O at the edges, and change structure only in small steps that tests pin down.

Fig. 1 is that idea on real code: the busiest endpoint of the chat API built on Building a backend API, before and after the ten-step refactor of section 9. Each slab is one line of the handler, as long as the line and indented as in the file, coloured by the concern it serves (by keyword rules, so a line or two is approximate).

  1. Before: five concerns in one function. The handler as it was: 52 lines, McCabe complexity 9, with authentication, rate limiting, idempotency keys, storage and the model call interleaved line by line.
  2. One concern, scattered. Pull the idempotency lines forward and they come out in pieces: the idempotency logic alone is split into 5 separate runs of lines, so changing that one rule means finding it in five places (low cohesion, section 1).
  3. After: 17 lines, complexity 4. The refactored handler reads top to bottom; each concern is now a call or two with a name that says what it is for.
  4. Behind each call, a module. Each concern's code moved into helpers, drawn behind the handler as Ousterhout draws modules: the red top is as wide as the entry helper's parameters, the height is the lines its helpers hide (idempotency 26, rate limit 14, database 11, auth 8, the model call 1). Small interfaces, much hidden: section 3.

Why this is the whole subject. Code is read far more often than it is written (PEP 8 credits the insight to Guido van Rossum), so the test of a design is the next change: code that works today but makes every change risky is bad code; code that is a little longer but where each change touches one place is good code. Every section below is one technique for that, with what it costs and when not to use it.

You need: Python and a little FastAPI; nothing else. Elsewhere: tests themselves are Testing and quality's (doubles, CI, mutation testing); language idioms, typing mechanics and the toolchain (ruff, uv, type checkers, packaging) are Python: typing, uv, packaging and the toolchain's; whole-system design is System design case studies'; HTTP API design is Service APIs', and the service behind it Building a backend API's.

Module, interface
any unit with an inside and an outside (function, class, file, package, service); everything a caller must know to use it: names, parameters, results, errors, side effects
Cohesion, coupling
how strongly the parts inside one module belong together; how much one module depends on the inside of another
Deep module
small interface, lots hidden behind it (Ousterhout); a shallow one hides little more than it exposes
Port, adapter
an interface the core defines for something it needs (a store, a model); the code that implements it for one technology
Functional core, imperative shell
decisions in pure functions; a thin outer layer does the I/O
Refactoring, characterization test
a change of structure that keeps behaviour; a test that records what code does today
Technical debt
design shortcuts whose cost is paid later as "interest" on every change that touches them

1. The enemy is complexity; cohesion and coupling are how you see it

John Ousterhout, who teaches software design at Stanford, defines complexity as "Anything related to the structure of a system that makes it hard to work on the development of that system" (his course notes; the book is A Philosophy of Software Design, 2nd edition July 2021). Its three symptoms: change amplification (a simple change needs many edits), cognitive load (you must hold a lot in your head to make a change) and unknown unknowns (something you needed to know was not obvious, or not even findable). Its two causes: dependencies (if one piece changes, another must too) and obscurity (it is not clear how or why the code works). It is "judged by readers of code, not the writer", and it is incremental: "an accumulation of thousands of small dependencies and obscurities".

The older vocabulary for the same thing is cohesion and coupling, from Stevens, Myers and Constantine, "Structured design" (IBM Systems Journal 13(2), 1974; Constantine had used the terms since the late 1960s). Paraphrased: a module is cohesive when everything in it serves one purpose, so a change of that purpose touches one place; two modules are coupled when one depends on the other's insides, so changing one forces a change in the other. Aim for high cohesion and low coupling. In the hero figure the "before" handler has low cohesion: auth, rate limiting, idempotency, storage and the model call interleave, so changing the idempotency rule means finding its lines in five places. Coupling is the cause Ousterhout calls dependencies; low cohesion produces his change amplification and cognitive load.

Kent Beck's four rules of simple design, in priority order, compress the goal (Fowler's summary, 2015): passes the tests, reveals intention, no duplication, fewest elements.

The running example
The chat product from the parent topic. Its API is a 200-line FastAPI service; its busiest endpoint, POST /v1/chats/{id}/messages, is one 52-line function that checks the API key, applies a rate limit, handles idempotency keys, stores the message, charges credits and "calls the model". It works, and it is exactly the kind of function that becomes hard to change. A second example, an LLM call that titles and summarises a chat, was written for this page in the tangled shape such code usually grows into.

2. Readable code: names, one level of detail, comments that say why

Names

PEP 8 fixes the spelling (lower_case_with_underscores functions, CapWords classes, ALL_CAPS constants, a leading underscore as the "weak internal use indicator"), and a formatter enforces it. The hard part is what a name says:

  • What it is, not how it is made. The handler has req_hash = hashlib.sha256(...); the refactor names the idea request_fingerprint(chat_id, body), so a reader learns what it is for (deciding whether two requests are "the same") without reading the hashing.
  • The unit in the name: timeout_s, max_chars, refill_per_s. A bare timeout=30 leaves every reader guessing: seconds or milliseconds?
  • Booleans read as questions (is_retryable, has_more), functions as verbs (claim_key, release_key, save_reply).
  • Length follows scope. r is fine for a response used on the next two lines; a module-level name must stand alone. data, info, manager, handle and process say almost nothing; they usually mean the thing has no single job yet.

One level of detail per function

A function should either say what happens in a few named steps, or do one of those steps in detail. Mixing the two forces the reader to switch between "the plan" and "the SQL" every few lines. Toggle the real handler (right): before, the rate-limit lines sit between the auth lines and the idempotency lines; after, each concern is one named line and the details live in functions you open only when you need them.

How short should a function be? Two experts disagree, usefully
Robert C. Martin's Clean Code (2008) pushes for very small functions. Ousterhout: "The advice in Clean Code on method length is so extreme that it encourages programmers to create teeny-tiny methods that suffer from both shallow interfaces and entanglement", and "Depth is more important than length: first make functions deep, then try to make them short enough to be easily read" (their written debate, September 2024 to February 2025; the second quote is from the 2nd edition extract). The practical rule: split when the pieces have names that explain them and can be understood alone; do not split when the reader would jump between five tiny functions to follow one idea.

Comments that say why

Code says what; a comment earns its place by saying what the code cannot: why, what it protects against, what was tried and rejected. PEP 8: "Comments that contradict the code are worse than no comments", and inline comments "are unnecessary and in fact distracting if they state the obvious" (its example: x = x + 1 # Increment x). Google's review guide asks for comments that "mostly explain why instead of what" (What to look for).

earns its place

API_KEYS = {sha256(b"sk_test_alice"): "alice"} # store a hash of the key, never the key# 1. claim the key atomically: the primary key makes a second insert fail

Says why (a leaked database must not leak keys) and what the code relies on (the primary key constraint), which no name can say.

noise

owner = who(authorization) # get the ownertokens -= 1 # subtract one token

Repeats the code. When the code changes, these are the comments that go stale and start to lie.

Cost. Renaming in shared code touches every caller and every open pull request; in a library it is a breaking change (section 12). Splitting adds jumps for the reader and pays only when the new names carry meaning. Do not docstring every private three-line helper "for completeness": a good name is shorter and cannot go stale.

The same handler, toggled: before, the concerns alternate line by line; after, one named call each

Read the handler line by line, coloured by concern

3. Deep modules and information hiding

An abstraction is "a simplified view of something that omits unimportant details" (Ousterhout's modular design notes). A module is worth its interface when it hides much more than it exposes: "Deep class: small interface, lots of functionality"; a shallow one has a complex interface or little behind it, so "invoking a method isn't much easier than just typing in the code of the method". His canonical deep module is Unix file I/O: a handful of calls (open, read, write, close and a seek) hide disks, caches, permissions and whole file systems. The idea is David Parnas's information hiding ("On the Criteria To Be Used in Decomposing Systems into Modules", Communications of the ACM, 1972), which Ousterhout calls "the single most important idea in software design".

Fig. 2 measures it on the refactored service (step 10): every function drawn the way Ousterhout draws modules, counted from the file by gen_data.py. A proxy: real interfaces also include errors, side effects and ordering rules, which no line count captures.

  1. Interface on top, what it hides below. Each block is one function of the service: the red top is its interface (as wide as the parameters a caller must supply), the height is what it hides (source lines of its body). Sorted by lines hidden per parameter, deepest first.
  2. The deep ones. claim_key hides 15 lines behind 3 parameters (the whole claim-or-replay dance with the database), take_token 9 lines behind 1 (a token bucket), save_reply 10 behind 4 (one transaction). A caller learns a name and a few arguments, and the rest can change without it.
  3. The shallow ones earn their place by their names. chat_exists and request_fingerprint hide one line each, make_reply one: they stay because their names say what a query or a hash is for. A shallow helper is fine when its name carries meaning; a shallow layer of them is classitis (below).
  4. Step 9: a rule leaks into the caller. claim_key was fairly deep, but the handler itself still had to call release_key on 2 separate paths (the 404 and the stream): the knowledge "a claimed key must be given back unless a response was saved" lived in the caller. That is information leakage.
  5. Step 10: pull it down. One context manager, idempotency_claim (3 parameters, 6 lines), wraps claim_key and releases the key on every exit without a saved response. The handler drops to 0 release calls and 13 lines; its interface to the key's lifetime is one with statement.

Three warnings from the same notes, each visible in the running example:

  • Classitis: "small classes taken to the extreme", each adding the least possible functionality, so the reader pays many interfaces for little. An LLMClientWrapper whose methods each call one SDK method is the everyday case: either hide something real (retries, typed errors, a smaller interface) or call the SDK directly.
  • Information leakage: one design decision known by several modules, so changing it means changing all of them. Its commonest cause is temporal decomposition: code split by the order things happen ("claim", then "release", then "save") instead of by what each piece knows. After step 9, claim_key was fairly deep, but the handler still released the key itself, on two paths (Fig. 2, step 4).
  • Pull complexity downwards: "Let a few module developers suffer, rather than thousands of users." Step 10 pulled the leaked rule down into one context manager, idempotency_claim, which releases the key on every exit without a saved response. The caller's interface got smaller, and a latent bug disappeared as a side effect: in steps 0 to 9, a crash after claiming a key left it "started" forever, so every retry got (measured; section 9).
How a shared function turns into the wrong abstraction

illustrative code written for this page in the running example's names; the sequence and the remedy are Metz's.

4. When to abstract: wait for the third copy, and back out of the wrong one

Every abstraction is a loan: it saves principal (duplicated code, places a change must touch) and charges interest (one more name to learn, one more jump when reading, one more shape every future change must fit). Two rules decide whether to take it.

The rule of three. "The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor." Popularised by Martin Fowler's Refactoring (1999) and attributed there to Don Roberts (1st edition, p. 58, quoted on the c2 wiki; also Wikipedia; the book is not online, so this is a secondary quotation). With two copies you cannot yet see which parts really vary; with three, the axis of variation is visible, so the abstraction is shaped by facts rather than guesses. The demo service's auth check appeared four times (one per endpoint), which is why step 8 of the refactor turns it into one dependency.

The wrong abstraction costs more than duplication. Sandi Metz: "duplication is far cheaper than the wrong abstraction" (The Wrong Abstraction, 2016; she notes the phrase circulated earlier). Step through how it happens and her remedy (green lines are new at each step):

  1. Two copies: wince, and leave them. Summary and title prompts both render a transcript. Two copies cannot yet show what varies.
  2. Third copy: extract render(). The export job needs it too. Now the variation (how many messages) is visible, so the function fits all three callers.
  3. A new case is almost like it: add a flag. Export wants timestamps. Adding a parameter and an if is the cheapest edit today.
  4. Repeat: a knot of flags every caller depends on. Evals want system messages hidden and tool calls redacted. Each caller passes a different mix of flags; nobody dares to change render().
  5. Back out: inline into every caller, keep only its branch. Metz's remedy. Each caller keeps the one or two lines it uses; what is left in common is small and real: formatting one message.

Her remedy, in her words: "Re-introduce duplication by inlining the abstracted code back into every caller", keep in each copy only the branch that caller uses, delete the rest, then look again for the real shared part. "When dealing with the wrong abstraction, the fastest way forward is back."

The ML version: premature platformisation
Building "the framework for all our training jobs" or "the generic LLM provider layer" before the second job or provider exists. The abstraction is shaped by imagination, the second real case does not fit, and it grows flags. Build the concrete thing twice; extract the platform from the working examples. (Carried from the old page; it is the rule of three applied to systems.)

Cheap reversibility beats prediction: prefer abstractions you can inline away (a function, a Protocol) over ones you cannot (a service boundary, a published API, a database schema), and decide those last, when you know most. When not to abstract: two copies that may diverge; a "generic" layer with one implementation and no test fake; a base class whose subclasses override most of it; a wrapper whose methods each call one method of the thing it wraps (shallow: it adds a name and hides nothing).

Config, plugins and entry points (when variation is data, or others extend you)
  • Declarative config over code when the variation is data-shaped: eval suites, model routing tables, pipeline definitions as YAML or JSON validated by pydantic. The DAG engine split is the model: the DAG definition is declarative, the operators are code. The trap: config that grows conditionals until it is a worse programming language. When config needs if/else, go back to code (or a real DSL with review and tests).
  • Plugin architectures when others must extend you without forking: a small stable interface (a Protocol), and discovery through entry points, a standard packaging mechanism "for an installed distribution to advertise components it provides" (spec). pytest finds plugins through the pytest11 entry point and its pluggy core "enables 1400+ plugins"; Airflow providers declare an apache_airflow_provider entry point; vLLM loads general plugins from the vllm.general_plugins group. Cost: a plugin interface is forever (Hyrum's law, quoted on Building a backend API), so start private and promote to a plugin API only under demonstrated demand.

5. Interfaces and dependency direction: ports, adapters, injection, validated edges

The demo service is one 200-line file, and at that size one file is right. Picture it at 5,000 lines with a second way in (a nightly batch job that summarises chats) and a second database (Postgres in production, SQLite in tests). Now "where does this code go?" decides how much has to change when one of those outside things changes. The organising idea is ports and adapters (hexagonal architecture), from Alistair Cockburn's 2005 article: "Allow an application to equally be driven by users, programs, automated test or batch scripts, and to be developed and tested in isolation from its eventual run-time devices and databases." The product's rules sit in the middle and know nothing about HTTP, SQL or a vendor's SDK; a port is an interface the middle defines ("something that can give me a chat's messages"), an adapter implements it for one technology (Postgres, SQLite, an HTTP client, a fake for tests).

Fig. 3 lays that service out as terraces, the rules on top (the names are illustrative; the structure is the one this section describes):

  1. The rules in the middle. domain/ holds the pure rules (fingerprints, prices, reply parsing) and ports.py the interfaces they need. It imports nothing from the project and knows nothing about HTTP, SQL or a vendor's SDK.
  2. Each layer imports only inward. api/ (the FastAPI routers) imports services/ (the use cases), which import domain/ and the ports. The arrows are imports, and they all climb toward the stable rules.
  3. The core defines the ports; adapters outside implement them. ChatStore and ChatModel are Protocols in ports.py (glass plates at the core's edge). postgres_store.py and http_model.py implement them (dashed) without the core knowing they exist.
  4. Calls flow out, imports point in. A request enters through api/, the use case calls the ChatStore port, and the call leaves through the Postgres adapter to the database (and through ChatModel to the model API). Control goes outward while every import points inward: that inversion is the whole trick.
  5. main.py builds and wires. The composition root builds the adapters (the database pool, the HTTP client, the settings) once at start-up and hands them to the app; nothing else calls os.environ or opens connections.
  6. Swap or fake an adapter. Swapping SQLite for Postgres touches one adapter file; a test plugs a fake into the same port and runs a use case with no network. The refactored LLM call's tests do exactly that (a FakeModel, a FakeStore, a scripted HTTP transport): 11 passed in 0.06s.
chat_service/ main.py # composition root: builds the adapters, hands them to the app config.py # settings read from the environment, validated once at start-up api/ # FastAPI routers: parse HTTP in, call a use case, render HTTP out. Thin. services/ # use cases: send_message, summarize_chat. Orchestrate; no SQL, no HTTP. domain/ # pure rules: fingerprints, prices, reply parsing. Imports nothing above. ports.py # Protocols the services need: ChatStore, ChatModel, RateLimiter adapters/ # postgres_store.py, sqlite_store.py, http_model.py, redis_limiter.py

Dependency direction is the rule that matters (steps 1 and 2): nothing imports api or adapters except main.py. The rule can be enforced in CI with import-linter (2.15, September 2026), whose "layers" contract fails the build when a lower layer imports a higher one. Where I/O lives: I/O is anything that leaves the process (network, disk, database, clock, randomness, environment variables). It is slow, can fail, and makes tests need setup, so push it to the edges: read what you need, decide in plain functions, then write the results (section 7 measures why).

A port in Python is a Protocol

A Protocol (PEP 544, Python 3.8, "static duck typing") declares the methods something must have; any class with matching methods satisfies it, with no base class and no import of the protocol. Prefer it to an abstract base class when the implementations live in other packages or in tests. (How the type checker treats it is Python: typing, uv, packaging and the toolchain, section 1's.)

class ChatModel(Protocol): def complete(self, system: str, user: str) -> str: ...# HttpChatModel (real HTTP) and FakeModel (tests) both satisfy it; neither mentions it.

Dependency injection without a framework

Dependency injection in Python is one habit: a function or class receives the things it uses instead of creating them. The tangled LLM call created its own database connection (sqlite3.connect(os.environ["CHAT_DB"])) and called a module-level httpx.post, so testing it means patching globals. The refactored one takes them as arguments:

def summarize_chat(chat_id: str, *, store: ChatStore, model: ChatModel) -> Summary: ...class HttpChatModel: def __init__(self, url, key, model="small", *, attempts=3, sleep=time.sleep, client=None): ... # real defaults; tests pass fakes

The unit test for the retry policy passes sleep=slept.append and an httpx client with a scripted transport; it checks that a 429 then a 503 are retried with waits of exactly 1 and 2 seconds, in milliseconds, without sleeping or touching a network (test_http_model_retries_only_transient_errors in src/llmcall/test_after.py). One place, the composition root (usually main.py), builds the database pool, the HTTP client and the settings once at start-up and passes them down; nothing else calls os.environ or opens connections. FastAPI already has injection: Depends(current_owner) in step 8 of the refactor is it, and tests swap a dependency with app.dependency_overrides. Pass fakes (small working implementations, such as an in-memory store) rather than mocks (objects that record calls and return canned values): the Review lab has a real test that still passes when the function it claims to test is broken (Testing and quality section 4 owns test doubles). Cost: parameters multiply, so give the common case a default (sleep=time.sleep); do not inject what never varies (the json module, pure helpers); a DI container library is rarely worth it in Python.

Cost. Every layer is a file to open and a name to learn. For a CRUD service whose "rules" are "store what the client sent", a service layer that only forwards calls to a repository is a shallow module: pure cost. Start with one module per feature (chats.py, billing.py); introduce a port when a second adapter actually appears (a test fake counts) or the rules grow beyond a screen.

Validate at the boundary, trust inside

A dataclass (standard library) generates __init__, __eq__ and __repr__ and checks nothing at run time; attrs does the same with more options. A pydantic BaseModel validates and converts every value when the object is built, raising an error that says which field and why. Validation is the point at an input boundary and wasted work everywhere else:

Nothing for one request, real money in a loop over ten million log rows. So: pydantic at the boundaries (HTTP bodies, LLM outputs, config read from the environment with pydantic-settings 2.15.0, files from outside), dataclasses or attrs inside.

Two surprises in the bars, and two signature habits

Two surprises: model_construct, the documented "skip validation" escape hatch, is slower here than validating (pydantic's performance notes and model docs warn that in V2 "for simple models, going with validation may even be faster"), and parsing JSON straight into a model (model_validate_json) beats json.loads plus a dataclass, which is why pydantic's docs say to prefer it. Two signature habits from the old page: accept abstract types, return concrete ones (take Sequence[Message] or Iterable; return list[Message]), and avoid "stringly typed" values (a str that is really one of five model names should be a Literal or an Enum).

A validated pydantic object costs about times a dataclass

real best of 7 runs of 100,000 constructions, nanoseconds per object, on an , Python , pydantic (pydantic-core ), attrs ; script src/bench/bench_models.py. Absolute numbers depend on the machine; the ratios are the point.

6. Composition over inheritance, and when patterns help

The Gang of Four's Design Patterns (Gamma, Helm, Johnson and Vlissides, 1994) states the principle in five words: "Favor object composition over class inheritance" (chapter 1; the book is not online). Inheritance reuses code by making a class a kind of another class, so the subclass depends on its parent's insides (tight coupling, and the coupling cannot be changed at run time). Composition reuses code by holding another object behind its interface, so each piece can be swapped or stacked. The difference shows the moment features combine:

Predict: two model providers, and you want retries, caching and logging in any combination. How many classes does each design need? Then press the feature buttons on the right.

Inheritance is still right for a true "is a" with a stable parent you control: an exception hierarchy (section 8), a framework's base class that is designed for it. Python's mechanics (the MRO, mixins, super()) are Python: the data model and protocols, section 5's.

Derived, illustrative names: with m providers and k optional features, a subclass per combination needs m × 2k classes (2 × 8 = 16 at three features, counting the plain one); wrappers that each satisfy the same ChatModel Protocol need m + k = 5 and are stacked at the composition root: Logged(Cached(Retrying(HttpChatModel(...)))). Each wrapper is testable alone with a fake inside it.

Patterns: a name for a variation you already have

A design pattern is a named, reusable shape for a recurring problem. It helps when the variation it handles already exists in your code (the third copy of section 4) and when the name speeds review ("this is a Strategy"). It hurts when applied before the variation exists, which adds the interest of an abstraction without the principal. Many classic patterns shrink in a language with first-class functions and modules: Peter Norvig found "16 of 23 patterns have qualitatively simpler implementation in Lisp or Dylan than in C++ for at least some uses of each pattern", for example Strategy, Command, Template Method and Visitor through first-class functions and Facade through modules (Design Patterns in Dynamic Languages, first presented 5 May 1996). Python has the same features:

PatternThe Python formHere
Strategypass a function (or an object satisfying a Protocol)sleep=time.sleep in HttpChatModel
Adaptera class that implements a port for one technologySqliteChatStore, HttpChatModel
Decorator (the GoF one)a wrapper satisfying the same ProtocolRetrying(HttpChatModel(...)) above
Factorya function, or the class itself (classes are callables)the composition root
Singletona module-level object, or better one built in main.py and injected; a singleton reached from everywhere is a hidden global (coupling)the HTTP client and database pool
Observera list of callbacks
Facadea module whose __all__ is the public surfacechatsummary/__init__.py (section 12)

When patterns hurt: an AbstractFactory with one product, a Visitor over a three-case union that a match statement says in six lines, a class with one method that should have been a function.

7. Functional core, imperative shell: a tangled LLM call, measured

A pure function returns a value computed only from its arguments and changes nothing outside itself; it is trivial to test (call, compare) and safe to reuse. Functional core, imperative shell is Gary Bernhardt's name for putting the decisions in pure functions (the core) and the I/O in a thin outer layer (the shell) .

The example: a function that gives a chat a title and a summary by calling an LLM. "Before" is the shape such code reaches after a few months of fixes: one function reads the database, builds the prompt, calls an OpenAI-style HTTP endpoint with retries, digs JSON out of the reply and writes the result. "After" does the same job as a core, two ports, two adapters and a six-line shell. Both were written for this page and run through the same seven situations with a scripted fake server (no network), counting HTTP calls and seconds spent sleeping between retries. Fig. 4 shows both, sized by the real files:

  1. Before: one function does everything. before.py's summarize(): 42 lines, McCabe complexity 14, every step of the job above inside one except Exception.
  2. After: a pure core inside an I/O shell. render_transcript (2 lines) and parse_summary (7 lines) sit on the glass plate: pure. summarize_chat (6 lines) is the shell. ChatStore and ChatModel are ports (Protocols, no body); SqliteChatStore (6 lines) and HttpChatModel (18 lines) are the only code that touches the disk or the network. Heights are lines of each body; cc is radon's complexity.
  3. Read at the edge. The shell asks the ChatStore port for the chat's messages; SqliteChatStore runs the query.
  4. Decide in the core. The messages go into render_transcript, which returns the prompt text. No I/O, so its test is a call and a comparison.
  5. Call the model through its adapter. The shell hands the prompt to the ChatModel port; HttpChatModel posts it and retries only what retrying can fix (429, 5xx, dropped connections), waiting 1 s then 2 s.
  6. Parse in the core, write at the edge. The reply goes into parse_summary, which returns a validated Summary or raises; the shell saves it through ChatStore.save_summary.
  7. The model refuses. Measured with a scripted fake server: before.py makes 3 calls, sleeps 7 s and returns None; after.py makes 1 call, and parse_summary raises ModelOutputError saying what came back.

The seven situations, side by side (pick one on the right):

In four of the seven situations "before" returns None, and in two of those only after three calls and seven seconds of sleeping, so a caller cannot tell "the model refused" from "our request is malformed" from "this chat is empty". The cause is one line: except Exception around everything, which turns every bug, including a KeyError in our own parsing and a 400 that says our request is wrong, into "retry and hope". "After" retries only what retrying can fix (429 and 5xx responses, dropped connections) and says what went wrong with a typed exception.

Read both versions in full

before.py

after.py

The core (render_transcript, parse_summary) is where the bugs were, and it now has unit tests that need no server, no database and no mocking library: for 11 tests. The shell (summarize_chat) is two lines of logic, so a handful of tests with fakes cover it.

Cost. "After" is longer ( source lines against ) and has eleven functions instead of one. For a one-off script you run by hand that is overhead: keep it tangled and short. It pays as soon as the code runs unattended, has more than one caller, or needs tests. One honest behaviour change: "before" silently cut titles to 200 characters, "after" rejects them as a model output error. That was a decision, and it belongs in the pull request description, not hidden in a refactor.

real both files run on with httpx and pydantic ; script src/llmcall/measure.py. Retry sleeps are recorded, not slept.

8. Error handling design: errors are part of the interface

Returning None for four different failures is the commonest error-handling mistake in Python services: the reason is thrown away, and the logs say summarize failed: 'choices' from inside a retry loop. PEP 20: "Errors should never pass silently. Unless explicitly silenced." Python's idiom is to raise an exception that travels up until a caller that can act catches it, in the style the glossary calls EAFP, "Easier to ask for forgiveness than permission" (glossary). The mechanics (chaining, groups, finally) are Python: the data model and protocols, section 6's; the design is four rules:

  1. One base class per package, so a caller can catch everything from you in one line: SummarizeError.
  2. One subclass per thing a caller would handle differently, not per place it can happen: ChatNotFound (show a 404), ModelOutputError (log, maybe try another prompt), ModelUnavailable (retry later).
  3. Say whether retrying helps in the type or an attribute (retryable = True), so retry code does not parse messages.
  4. Keep the cause: raise ModelOutputError(str(e)) from e chains the original, so the traceback shows both.

Where to catch: where you can do something (retry, fall back, or turn the error into a response). In the refactored service that is one place: a single exception handler turns every ProblemError into an RFC 9457 problem response (step 2 of the refactor; the HTTP side is section 2 of Service APIs). Everywhere else, let exceptions travel. Catching just to log and re-raise doubles every log line; catching Exception "to be safe" is the bug measured in section 7 (ruff flags it as BLE001, blind except).

Define errors out of existence (Ousterhout, exceptions notes: "Whenever possible, define errors out of existence"): choose semantics where the awkward case is not an error. set.discard(x) does nothing if x is absent (set.remove raises), os.makedirs(path, exist_ok=True), dict.get(key, default); in the refactor, idempotency_claim releasing the key on every exit removes a whole category of "forgot to release" errors.

Cost. A hierarchy is interface: every class you publish is a promise (section 12). Do not create one exception class per function. Exceptions are slow-ish in tight loops and wrong for expected outcomes ("no more pages" is a return value, not an error).

Note on the old page and on the SDK's HTTP library (checked 2026-10-04)

The old page described the retry pattern correctly. Two things changed since: the SDK is now at major version 3, and its README says its clients are "powered by HTTPX2" (pydantic's fork of httpx), whose exception tree mirrors httpx's (httpx: HTTPError splits into RequestError, with TransportError and its timeouts below it, and HTTPStatusError; docs). Code that caught httpx.TimeoutException around SDK calls should catch the SDK's own APITimeoutError instead: depend on the interface the library publishes, not on what it happens to use inside.

A real hierarchy: the type says whether the SDK retries
OpenAIError└ APIError ├ APIConnectionError # could not reach the server: retried │ └ APITimeoutError # retried └ APIStatusError # the server answered with an error status ├ BadRequestError (400), AuthenticationError (401), PermissionDeniedError (403), │ NotFoundError (404), UnprocessableEntityError (422) # our fault: not retried ├ ConflictError (409), RateLimitError (429) # retried └ InternalServerError (5xx) # retried

The OpenAI Python SDK at v3.24.0 (_exceptions.py). Its README: "Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and >=500 Internal errors are all retried by default", 2 times with a short exponential backoff, and "Requests are retried only when their body can be safely resent". after.py copies the policy at small scale: only TransportError, 429 and 5xx are retried. Retry policy as a whole (backoff, jitter, budgets) is Reliability engineering's.

The real handler refactored in ten tested steps, against one rewrite
Bars: handler lines (52 at most). Dots: complexity, on a 0 to 10 scale. Numbers: steps; R: the rewrite; ✗: a test fails at that step.
The handler at this step (green lines are new since the previous step)
The full diff of this step (whole file)

real 14 characterization tests written first (one more joins at step 10); after every step src/refactor/run_steps.py ran them and measured, on (pytest , radon , ruff with rules ). "Complexity" is McCabe cyclomatic complexity of the handler, computed by radon.

9. Refactoring safely: pin behaviour with tests, then small steps

Martin Fowler's definition: a refactoring is "a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior". If behaviour changes, it is not a refactoring and belongs in a separate, reviewed change. His book Refactoring (1999; 2nd edition 2018, examples in JavaScript) is a catalogue of small, named, safe moves: Extract Function, Inline Function, Rename Variable, and dozens more. For code with no tests, Michael Feathers (Working Effectively with Legacy Code, 2004) named the first tool: a characterization test, whose purpose "is to document your system's actual behavior, not check for the behavior you wish your system had" (Feathers, 2016): call the code, record what it does today, even if it looks wrong, and assert exactly that. His blunt definition from 2002: "The main thing that distinguishes legacy code from non-legacy code is tests, or rather a lack of tests." Then the loop: one small change, run the tests, commit; when a test goes red you know exactly which change did it, and undoing it costs seconds. Kent Beck: "for each desired change, make the change easy (warning: this may be hard), then make the easy change" (2012, quoted by Fowler).

Predict: ten small steps, or one rewrite to the same design. Which keeps all 14 characterization tests green, and which ends with the lower complexity score?

Press the modes on the right; each step below is one commit, tested and measured.

  1. The handler as it is. The real send_message from the backend API page's demo service: 52 lines doing authentication, rate limiting, idempotency, storage and the model call inline, complexity 9. Ruff's PLR0911 (too many return statements, default limit 6) fires on it.
  2. Pin the behaviour with tests. 14 characterization tests record what the handler does today, good or bad. Nothing in the code changes.
  3. Errors become exceptions. A ProblemError exception and one handler that turns it into an RFC 9457 response. The handler raises instead of building responses, so a helper can fail without returning a special value, and PLR0911 stops firing once errors are raised instead of returned.
  4. Extract enforce_rate_limit(). Five lines about tokens become one call with a name. The helper raises 429 itself and returns the headers the success response needs.
  5. Name the fingerprint: request_fingerprint(). A pure function: same inputs, same output, no database. The handler stops spelling out how a request is hashed.
  6. Extract claim_key(). The 15-line try/except that claims a key moves behind one name. It returns a saved response to replay, or None when this request now owns the key.
  7. Name the duplicate: release_key(). The same DELETE appeared twice. A named function says why it runs (give the key back) and keeps the two copies from drifting apart.
  8. Split core from shell: make_reply() and save_reply(). Deciding the reply is pure (make_reply); writing it is I/O (save_reply: one transaction); the handler only wires them together. Steps 1 to 7 change structure only, and the tests prove it: 14 of 14 green every time. Complexity falls from 9 to 6 and the handler from 52 to 28 lines.
  9. Auth becomes a dependency, and a test goes red. Every endpoint repeated the same three auth lines; a FastAPI dependency raises 401 once for all four. Moving authentication into a FastAPI dependency changed which error wins when a request has no API key and an invalid body: 401 now, 422 before, because dependencies run before body validation. No reader of the diff would have spotted it; the characterization test did.
  10. Decide, then tidy. It is a behaviour change, so it gets a decision: identity first is the better behaviour (an unknown caller should not learn how its body is wrong), so this step updates the test in its own commit, which a reviewer approves on its own; then the handler is tidied to read top to bottom at one level of abstraction.
  11. Deepen: one object owns the key's lifetime. Steps 5 and 6 left the handler releasing the key on two paths; a context manager now claims the key and releases it on every exit that did not save a response (section 3). That fixed something no test covered: in steps 0 to 9, if the handler crashed after claiming a key (simulated by making ID generation fail), the retry got forever; at step 10 it gets . A new test now pins the fixed behaviour.

Cost. Characterization tests first are real work (here, 14 tests for one handler), and refactoring takes review time that ships no feature. Do not refactor code that is about to be deleted, code nobody needs to change, or during an incident. Never mix a refactoring and a behaviour change in one pull request: the reviewer cannot tell which line is which.

About the complexity numbers (McCabe, radon, ruff thresholds)

McCabe's cyclomatic complexity counts independent paths through a function (roughly, 1 plus the number of decision points). His 1976 paper proposed 10 as "a reasonable, but not magical, upper limit" (McCabe, IEEE TSE, 1976, scanned copy); ruff's C901 uses 10 by default and radon grades 1 to 5 as A and 6 to 10 as B (radon docs). The original handler scored 9, under every threshold, and was still the hardest function in the service to change. Metrics find candidates; they do not judge design. The rewrite's score of 2 is the proof: the lowest number on the chart belongs to the broken version.

10. Code an LLM agent can change safely

A coding agent edits, runs something, reads the result and edits again. It stops when the work looks done, so the design question is what it can check and how much it must read. Anthropic's Claude Code guidance puts both constraints plainly: "Give Claude a check it can run: tests, a build, a screenshot to compare", and "Claude's context window fills up fast, and performance degrades as it fills" (Best practices for Claude Code, page updated 2026-10-20, read 2026-10-24). Everything in sections 1 to 9 serves an agent for the same reasons it serves a human, with less slack:

  • A check it can run: characterization tests before a change (section 9), types on signatures, a linter with bug-finding rules. The narrower the check, the sooner the loop closes.
  • Seams: ports and injected collaborators (section 5) let the agent run the core with fakes, in milliseconds, without network or credentials.
  • Small, cohesive files with names that say what things are for: the agent reads only what the change needs, which keeps its context small (section 2). A 17-line handler that calls idempotency_claim is cheaper to load than 52 interleaved lines.
  • Invariants written down: state what must always hold ("a claimed key is released unless a response was saved") in a docstring or test name, and check the change against that sentence.
  • Never let it edit the tests and the code in the same step to make a failure go away; that is how a characterization test gets "fixed" instead of the bug. Keep diffs small, one change at a time, as for humans.
  • Check every new dependency exists and is the package you think it is: across 16 models and 576,000 code samples, "the average percentage of hallucinated packages is at least 5.2% for commercial models and 21.7% for open-source models", with 205,474 unique invented names (Spracklen et al., USENIX Security 2025). Attackers register such names ("slopsquatting"), so pip install of an unknown suggested package can install malware.

Plausible is the risk: the failure mode is code that looks right, passes the tests it wrote for itself, and is subtly wrong at the edges. Reviewing what comes back is the same review as for a human, with a higher bar ("LLM-authored code raises the review bar, not lowers it", from the old page): read the tests first (do they test behaviour, or mocks?), then the edges assistants handle worst (error paths, retries, empty inputs, concurrency, time zones). The "retry everything" and "blocking call in async code" diffs in the Review lab are both typical. Where tests are silent on very large or AI-written changes is Testing and quality's section 13; the harnesses that run agents are Topic: agentic-harnesses; how coding agents are benchmarked, and why scores can mislead, is Agentic benchmarks and the paper page Schrödinger's Code Repository (has an LLM learned SWE-bench or memorised it?).

What the evidence says about AI and speed (dated, as of 2026-10-04)
  • Speed is not settled. METR's randomised trial (16 experienced open-source developers, 246 real issues in their own repositories, early-2025 tools) found "when developers use AI tools, they take 19% longer than without", while the developers expected a 24% speedup and still believed afterwards that AI had sped them up by 20% (METR, 2025-07-10). A February 2026 follow-up with newer tools says its new data "gives us an unreliable signal of the current productivity effect of AI tools", because of who chose to take part (METR, 2026-02-24). Honest summary: no reliable measurement yet, and your own feeling of speed is not evidence.
  • Delivery can suffer. Google's DORA 2024 report associated a 25% increase in AI adoption with 7.5% better documentation quality and 3.4% better code quality, but also "an estimated decrease in delivery throughput by 1.5%, and an estimated reduction in delivery stability by 7.2%" (Google Cloud blog, 2024-10-23).
The agent's loop closes only where the code gives it a check it can run

Static diagram. Evidence from this page's own runs: the characterization tests caught step 8's 401 against 422 (section 9); mypy --strict found 1 error in the unannotated tangled call and so would not guard it (depth block "Types"); ruff's BLE001 flags the blind except Exception of section 7. Where no check exists, "looks done" is the only signal, and the reviewer becomes the loop.

11. Technical debt is a decision

Ward Cunningham coined the metaphor in his OOPSLA 1992 experience report: "Shipping first time code is like going into debt. A little debt speeds development so long as it is paid back promptly with a rewrite", and "Every minute spent on not-quite-right code counts as interest on that debt" (The WyCash Portfolio Management System). The useful part is the decision it frames: debt is fine when it buys something and its interest is small; it is a problem when nobody chose it or nobody pays it down.

  • Interest is paid only where you change code. Fowler: "The prudent debt to reach a release may not be worth paying down if the interest payments are sufficiently small - such as if it were in a rarely touched part of the code-base." So pay down where change is frequent: the busiest handler, not the yearly report script.
  • Write the decision down: a ticket or a comment that says what was skipped, why, and what would trigger paying it (a second provider, a second caller). The tangled LLM call is fine as a one-off script; the trigger to restructure it is "runs unattended or gains a second caller" (section 7).
  • Pay in small refactorings, not a rewrite (section 9): each step ships, keeps the tests green and can stop at any point when the interest is low enough.
  • "Quick and dirty" is usually reckless: Fowler agrees with Robert Martin that choosing it "because they think they can't afford the time required to write clean code" underestimates where the design payoff comes, since "The whole point of good design and clean code is to make you go faster".
Two questions sort any shortcut: did we know, and was it sensible?

Martin Fowler's Technical Debt Quadrant (14 October 2009): "the useful distinction isn't between debt or non-debt, but between prudent and reckless debt", and "there's also a difference between deliberate and inadvertent debt". The cell texts paraphrase his examples. Prudent and inadvertent debt is, in his words, "not just common but inevitable for teams that are excellent designers": you learn what the design should have been by building it.

12. Designing a Python library

A library is code whose callers you do not control: another team, the open-source world, or you in another repository. Every rule above gets stricter, because you cannot fix the callers when you change something. The bar the old page set: a colleague can use the package correctly from the type signatures alone. To make it concrete, the refactored LLM call was packaged as a real library, chatsummary 0.3.0 (in src/libdemo/), and built.

A small, explicit public surface

PEP 8: "Any backwards compatibility guarantees apply only to public interfaces", and modules "should explicitly declare the names in their public API using the __all__ attribute". The reason to be strict is Hyrum's law (quoted on Building a backend API): with enough users, every observable behaviour will be depended on by somebody, documented or not, so the smaller the surface, the less you are stuck with.

# chatsummary/__init__.py: the public API is exactly this list__all__ = ["summarize_chat", "render_transcript", "Summary", "Message", "ChatModel", "ChatStore", "HttpChatModel", "SqliteChatStore", "SummarizeError", "ChatNotFound", ...]# everything else lives in chatsummary/_core.py: the underscore says "internal, may change"
  • One obvious entry point (summarize_chat); everything else supports it.
  • Keyword-only options. A bare * in the signature (PEP 3102) forces summarize_chat("c1", store=s, model=m): call sites say what each argument is, and you can add or reorder options later without breaking anyone.
  • No boolean positional flags. summarize(chat, True) means nothing at the call site; summarize(chat, force=True) does, and two behaviours behind one flag are often two functions.
  • Typed, and say so. PEP 561: packages that support type checking "MUST add a marker file named py.typed". The built wheel holds exactly: ; mypy --strict on it: "".
  • Exceptions are interface (section 8): one base class, exported.

Versions and deprecation: change a public name without breaking anyone

Semantic Versioning 2.0.0: given MAJOR.MINOR.PATCH, increment MAJOR "when you make incompatible API changes", MINOR "when you add functionality in a backward compatible manner", PATCH "when you make backward compatible bug fixes"; and "Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable." That is why users pin 0.x libraries tightly (pydantic>=2.7,<3 pins a major; for a 0.x dependency pin the minor). For HTTP APIs the same judgement (which change breaks a client) is section 2 of Service APIs.

Correction to the old page: how long to warn
The old page said "deprecate with DeprecationWarning one minor version before removal". Python's own policy, PEP 387, asks for more: "Wait for the warning to appear in at least two minor Python versions of the same major version", and "It is preferred, though, to wait 5 years before removal". That is CPython's rule, not a law for every library, but "at least two releases" is the safer default. Two facts the old page missed: PEP 565 makes DeprecationWarning visible by default only for code running directly in __main__, so your users' applications usually do not show it; their test runs do, since pytest displays it by default (pytest docs). For warnings meant for end users of an application, the warnings docs point to FutureWarning.

Cost. A published library turns every refactor into a compatibility question. Inside one monorepo, an internal module whose callers can all be changed in one commit needs no semver or deprecation shims: change the callers. Promote code to a library only when callers live in places you cannot edit.

Packaging with pyproject.toml: the real file (the toolchain itself is Python: typing, uv, packaging and the toolchain's)

Everything about a package lives in pyproject.toml: its metadata (PEP 621), the build backend that turns source into a wheel (PEP 517 and 518) and tool settings. The real file used to build chatsummary:

A wheel is the built, installable archive (). In 2026 most teams create and manage projects with uv (0.12.23, 2026-10-03): uv init --lib, uv add pydantic, uv build, uv publish. The src/ layout (code under src/chatsummary/) prevents tests from accidentally importing the source folder instead of the installed package. Wheels, tags, ABIs and trusted publishing are taught in Python: typing, uv, packaging and the toolchain, section 7.

Renaming max_chars to limit: accept both, warn for two releases, then remove
def render_transcript(messages, *, limit: int = 8000, max_chars: int | None = None) -> str: if max_chars is not None: warnings.warn("render_transcript(max_chars=...) is deprecated since 0.3.0 and will be removed in 0.5.0; " "use limit=...", DeprecationWarning, stacklevel=2) limit = max_chars return _render_transcript(messages, limit)

real called with the old name it still works and emits "", pointing at the caller's line () thanks to stacklevel=2. Without the shim, the same call fails outright: (from the Review lab).

13. Code review: better, not perfect

A code review is a second engineer reading a change before it merges (Google's guide says CL, for changelist; GitHub says pull request). It catches bugs, but its bigger jobs are spreading knowledge and keeping the codebase consistent. The best free reference is Google's published guide, Google Engineering Practices. Its standard: "In general, reviewers should favor approving a CL once it is in a state where it definitely improves the overall code health of the system being worked on, even if the CL isn't perfect" (The Standard of Code Review). Holding out for perfection teaches authors to batch changes into huge PRs that are even harder to review.

Spend attention in this order (from the old page, consistent with Google's What to look for: design, functionality, complexity, tests, naming, comments, style, consistency, documentation, every line, context, and good things):

  1. Is the approach right? Does this belong here? A wrong approach makes every line comment moot.
  2. The interface: names, signatures, errors, anything other code will depend on (sections 3, 8 and 12).
  3. Tests: would they fail if the code were wrong? (The Review lab has a real test that passes with the function broken.)
  4. Naming and clarity: could you change this code in six months?
  5. Style: last, and ideally never. If a human is commenting on formatting, automation is missing.

Writing a comment. Label the weight: "If it's not very important, prefix it with something like "Nit: "" (comments guide); the Review lab uses blocking question nit praise. About the code, never the developer, and explain why: "this retries 400s, which are our bugs, three times" teaches; "wrong" does not. Ask when the author has more context ("what happens if the chat is deleted mid-stream?"). Say what is good: "good things" is on Google's list because it tells the author what to keep doing.

Size and speed. "100 lines is usually a reasonable size for a CL, and 1000 lines is usually too large, but it's up to the judgment of your reviewer" (Small CLs); "One business day is the maximum time it should take to respond to a code review request" (Speed): to respond, not necessarily to finish. Review is a queue: a change waiting a day is a day of latency for every change behind it, which is the reason behind both numbers.

Practise on the Review lab: eleven real diffs to this page's code, each flagged problem demonstrated by running it. This page owns review and static checks as craft; running them as CI gates (which check runs first, what blocks a merge) is Testing and quality's section 12.

Correction to the old page: the "90% of defects" figure
The old page said "reviewers find 90% of defects in the first few hundred lines". The source usually behind it, SmartBear's study of a Cisco team, says something narrower: "developers should review no more than 200 to 400 lines of code (LOC) at a time", "beyond 400 LOC, the ability to find defects diminishes", and "a review of 200-400 LOC over 60 to 90 minutes should yield 70-90% defect discovery", with inspection rates under 500 LOC per hour (SmartBear, undated page; the study is reported in Jason Cohen's Best Kept Secrets of Peer Code Review, 2006). One company's study published by a vendor that sells review tools: read it as direction (small reviews, slow reading), not as a law. The conclusion stands; the number was wrong.
Taking review (the author's side)

Google's author guide (handling comments): "Don't Take it Personally", and "If a reviewer says that they don't understand something in your code, your first response should be to clarify the code itself": a reply helps one reader once, a clearer name helps every reader after. Write the PR description for a reviewer with no context (what changed, why, how it was tested, what you are unsure about), and split refactorings from behaviour changes so each PR answers one question.

ML-specific review habits (from the old page)
  • Config and prompt diffs deserve the same scrutiny as code: a changed prompt is a changed program.
  • Ask "what eval covers this?" the way you ask "what test covers this?" (see Production eval engineering for how evals run in CI).
  • Check seeds and determinism in training changes.
  • Be suspicious of notebook code moving to production without an interface (a function with a typed signature and tests).

Depth: types and tooling at the design level

Closed blocks. The language mechanics of typing and the toolchain are Python: typing, uv, packaging and the toolchain's (sections 1 to 5); what stays here is what they mean for design, with the versions as of 2026-10-04.

Types: hints, checkers, overloads, and an unannotated trap

Python does not check types when it runs: def f(x: int) happily accepts a string. A type hint (PEP 484, written 2014, Python 3.5) is an annotation for tools; a type checker reads the hints without running the code and reports calls that cannot work (passing None where a str is required, forgetting that a lookup can fail, misspelling an attribute): a whole class of bugs found in seconds at your desk, plus documentation that cannot go stale because CI checks it.

def summarize_chat(chat_id: str, *, store: ChatStore, model: ChatModel) -> Summary:def claim_key(owner: str, key: str, fingerprint: str) -> JSONResponse | None:role: Literal["user", "assistant", "system"]

Read them as sentences: JSONResponse | None ("a response, or nothing"; the | spelling is PEP 604, Python 3.10) forces every caller to handle the nothing; Literal[...] limits a string to known values, so a typo like "asistant" is caught; the bare * makes everything after it keyword-only.

Four checkers exist: mypy (2.4.0, the reference), pyright (Microsoft, inside VS Code's Pylance), ty (Astral, a 0.0.x beta) and pyrefly (Meta); their versions, strict settings and how they disagree on the same code are in Python: typing, uv, packaging and the toolchain, section 2.

What pros do: pick one checker, run it in CI and in the editor, and make new code pass its strict mode while old code is brought in module by module. Two checkers disagreeing on edge cases is normal; running two is rarely worth it.

A trap, measured: an unannotated function is nearly invisible to the checker
Run on the tangled LLM call (before.py), mypy --strict reports error: "". Not one of its real problems. Without annotations every parameter is Any, and Any is compatible with everything, so there is almost nothing to contradict. Type checking pays only once the signatures carry types. after.py, fully annotated: errors under the same flags, and now a wrong call would be caught.

Overloads, when the return type depends on an argument. The official OpenAI SDK (v3.24.0, 2026-10-02) types chat.completions.create with @overload: with stream: Literal[True] it returns Stream[ChatCompletionChunk], otherwise a ChatCompletion (source at the tag), so iterating over a non-streamed reply is an error at your desk. Also: NewType("ModelId", str) so a model id cannot be passed where a chat id is expected, and generic functions with PEP 695's def first[T](xs: Sequence[T]) -> T (Python 3.12).

Cost. Annotations take time to write, and the checker has opinions about dynamic code (decorators, **kwargs plumbing, ORMs) that can take an hour to satisfy. # type: ignore[code] with the specific code is the honest escape. Do not chase strict mode in a throwaway notebook.

Tooling: let machines check the mechanical parts (versions as of )
JobTool (PyPI version, release date)What it does for you
Lint and formatruff 0.16.10, 2026-10-01One tool for hundreds of lint rules (pyflakes, pycodestyle, isort, bugbear, pylint subsets) and a formatter; its docs claim "10-100x faster than existing linters (like Flake8) and formatters (like Black)". The formatter is "designed as a drop-in replacement for Black": on Django and Zulip "> 99.9% of lines are formatted identically" (docs). Black itself (26.10.0, released 2026-10-04) is still maintained.
Type checkmypy 2.4.0 or pyright 1.1.414 (ty, pyrefly newer)The block above.
Run checks before each commitpre-commit 4.6.2, 2026-08-10Runs the hooks listed in .pre-commit-config.yaml on the files you changed, at git commit, so formatting never reaches review.
Projects, dependencies, Python versionsuv 0.12.23, 2026-10-03Creates projects, resolves and locks dependencies (uv.lock), installs Python itself, builds and publishes.
Testspytest 9.1.1; hypothesis 6.168.3Owned by Testing and quality, which also covers CI.

The real configuration that built chatsummary, plus the pre-commit file that would run it (the ruff hook block is the one from ruff-pre-commit's README; tags checked 2026-10-04):

# pyproject.toml (tool sections)[tool.ruff]line-length = 110target-version = "py310"[tool.ruff.lint]select = ["E", "F", "I", "B", "UP", "BLE", "C901", "PLR0911", "PLR0912", "ANN"][tool.mypy]strict = true# .pre-commit-config.yamlrepos:- repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.16.10 hooks: - id: ruff-check args: [ --fix ] - id: ruff-format- repo: https://github.com/pre-commit/mirrors-mypy rev: v2.4.0 hooks: - id: mypy additional_dependencies: [pydantic, httpx]

Rule selection is a decision, not a default: ruff enables only a small default set, and C901 (complexity) is not in it. What a few chosen rules found on the tangled LLM call, for real:

Cost. Every rule you enable is a rule someone must satisfy or silence. Turning on everything (select = ["ALL"]) on an old codebase produces thousands of findings and teaches people to ignore the linter. Start with the defaults plus a few rules that catch bugs (bugbear B, blind except BLE), add more one at a time, and fix or baseline existing violations when you do.