Skip to content

ADR 0072: Generators as state machines

Status: Final Type: Feature Created: 2026-11-06 Amends: 0064 (a generator the inlining cannot take is lowered as a state machine, so a recursive generator and one held in a name leave the refused list) Related-ADRs: 0023 and 0024 (the frame is an instance, released as one), 0007 (an exception leaving the generator), 0053 (a yield defeats a loop's proof, notes/accept-then-wrong.md §76)

Context

ADR 0064 lowers a generator by writing its body into the loop that consumes it, which needs no frame and costs nothing at run time. It refuses the shapes it cannot write in: a generator held in a name and consumed later, or one that consumes itself, which would be written into itself without end. ADR 0064's alternatives named the answer, a frame per generator object holding the locals and the yield it stopped at. They also named the programs that would need it: sudoku5's solve and mwmatching's blossomLeaves, both recursive. The owner chose it (A187).

Decision

  1. The inlining stays the first answer. A call ADR 0064 lowers is lowered as before. A frame is made only where the inlining cannot be used: a generator consuming itself, directly or through another, or a frame held in a name, a local or a module global, and consumed by a later loop.
  2. Which generators. A module-level generator function qualifies when all parameters are annotated, with constant defaults and no *args, **kwargs or keyword-only parameter, when it defines no function or class and has no yield inside a try or a with, and when the return is annotated Iterator[T], Iterable[T] or Generator[T, None, None]. T is what the frame produces. Any other generator keeps ADR 0064's refusals, which now say which of these it misses.
  3. The frame is an instance of a class the compiler makes for the generator. The fields are the state, the arguments, and every value live across a yield. The live values are found from the IR once the body is lowered, so a loop's hidden counter, a range's bound and an inlined generator's own state are kept with the locals. The frame is counted and released as any instance is (ADR 0024). A value the frame's function owned moves into a field at the yield and back at the resume. A value it only borrowed is held by the field while the generator is suspended, as CPython's frame holds it.
  4. Two functions. The constructor, named as the generator, so a call of it is an ordinary call: it allocates the frame and stores the arguments. The resume function has the generator's body. Its entry dispatches on the state: to the start, to the point after the yield it stopped at, or, finished, to the end. A frame resumed while it runs raises CPython's ValueError: generator already executing. A yield v returns v and records where to resume; the end of the body, a return and an exception leaving it finish the generator.
  5. What consumes a frame. A for, a comprehension, and list, sorted, sum, min, max, set, any, all or join of it, each resuming it until it finishes. An exception it raises leaves through the consumer's handlers. A break leaves it suspended; a later loop over the same frame resumes it where it stopped, as CPython's does.
  6. How the rest of the program sees a frame. The repr is CPython's, <generator object g at 0x…>, with this runtime's address (A179). == and hashing are identity, as CPython's. It has no attribute a program can read. copy.copy and copy.deepcopy of one are refused, where the compiler sees the frame, and stop the program where it does not, as a file's copy does (CPython raises TypeError: cannot pickle 'generator' object).
  7. What a frame does not do yet is listed on the compatibility page. Two of those items wait on more than work: next() raises StopIteration, which PEP 479 turns into RuntimeError as it leaves a generator. A generator written into its consumer has no edge to turn it at. A yield inside a try or a with needs its finally or __exit__ run when a suspended frame is dropped.

Consequences

  • A module whose generators are all inlined compiles to the IR it compiled to before: a machine is lowered only when a lowered function calls it.
  • A frame costs a heap allocation per call and a dispatch per value. A recursion d deep passes each value up through d frames, as CPython's nested for/yield does.
  • Designing this found three defects in the inlining it keeps, each fixed: a proven loop read a list the consumer had cleared (notes/accept-then-wrong.md §76); a name the generator bound inside a block was not renamed apart from the consumer's (§77); and a yield before a loop made the loop's bound undominated, which crashed the verifier.

Alternatives considered

  • The consumer's body as a callback the generator calls at each yield, for a recursive generator consumed in place: smaller, but a second partial mechanism, with mutable captures and a stop flag for break; it has no answer for a held generator.
  • The frame's fields from the source's locals: misses the values the lowering itself keeps across a yield: a generator suspended inside a loop keeps its place in them.
  • Every generator as a state machine: an allocation per call where the inlining is exact and free.