Readable Python A style bookletContents

A style booklet for ML systems code · 15 rules · 11 chapters

Readable Python.

Code that reads like the best serving engines: open the main loop, and understand the system from one screen.

This is not a formatting guide. Let ruff format and a lint config settle spacing, quotes and import order, and never discuss them in review. Everything here is about structure: where state lives, how a loop is shaped, what a comment is for. Those are the things that make code easy or hard to follow, and no tool can fix them.

Each chapter states its rules, then shows a draft struck through in red and the revision beside it. The examples are small on purpose; the patterns scale.

The fifteen rules

  1. Optimize for the reader. Code is read far more often than it is written. When writing it is easy and reading it is hard, rewrite.

    Chapter 1
  2. The top-level loop is a list of named steps. A reader should see the whole system in one screen.

    Chapter 2
  3. One class, one job. Data crosses boundaries as dataclasses.

    Chapter 2
  4. Every piece of state has exactly one owner. No parallel dicts kept in sync by hand.

    Chapter 3
  5. Use an enum for status, not a pile of booleans.

    Chapter 3
  6. Functions return results. They don't mutate their arguments.

    Chapter 4
  7. One level of abstraction per function, and at most four parameters.

    Chapter 4
  8. Name things with domain words, and use the same word for the same thing everywhere.

    Chapter 5
  9. Comments say why. The code says what. Git says when.

    Chapter 6
  10. Fail loudly at boundaries. Decide what's recoverable in one place. No blanket except Exception.

    Chapter 7
  11. Each piece of mutable state belongs to one thread. Hand off with queues.

    Chapter 8
  12. Only overlap work that uses different hardware, and prove it with a profile.

    Chapter 8
  13. Add an abstraction at the second implementation, not the first.

    Chapter 9
  14. Tests describe behaviour, one idea per test.

    Chapter 10
  15. Review AI-written code for what to delete.

    Chapter 11

Contents

  1. PrinciplesRP01
  2. The shape of a systemRP02–03
  3. StateRP04–05
  4. FunctionsRP06–07
  5. NamingRP08
  6. Comments and docstringsRP09
  7. ErrorsRP10
  8. Concurrency and the GPURP11–12
  9. AbstractionsRP13
  10. TestsRP14
  11. Reviewing AI-written codeRP15

How to use it

Set in Newsreader, Instrument Sans and IBM Plex Mono. The red is the editor's pencil: it marks rules, chapter numbers and struck drafts, and nothing else.