ADR 0076: Closures, functions that capture¶
Status: Final
Type: Feature
Created: 2026-11-14
Amends: 0070 (a function value is a counted closure object, called through its code with the closure first), 0010 (a captured name rebound after the def, or written with nonlocal, is a cell where it was refused)
Related-ADRs: 0024 (the header, the descriptor and the slot rule a closure reuses), 0023 (the instance a closure's layout follows), 0065 (the class number in the header). Provenance: A184, A196, 0.3's task 10.
Context¶
ADR 0070 made functions values without capture. A function value is a bare address, with no room for the variables a nested function reads from the enclosing one. So a nested def or a lambda that captures is lowered only where it is called directly: ADR 0010 lifts it to a top-level function whose captures become leading parameters, read in the calling frame. Returning it, passing it or storing it is refused, and so is any capture Python's cell would tell apart from a copy: a name the enclosing function rebinds after the def, binds in a loop around it, or that the nested function writes with nonlocal (PP007).
0.3's task 7 ranked what the corpora still meet (notes/measurements.md, 2026-11-14). Closures come first among the tasks, in five p2w programs:
- A nested function returned, reading a parameter of its maker:
make_adder(x)returningadd,make_linear(a, b),make_greeter(greeting),compose(f, g), nested a level further inmake_multiplier(x)(y)(z), and the same as a lambda,return lambda x: x * n(chained_calls,closures_nested,lambda). nonlocal, called in place (level1'slevel3settingvalue,multi_nonlocal'smodifysettingaandb) and returned (make_counter'sinc, which incrementscounton each call) (global_nonlocal,scope).- A list of functions,
ops = [lambda x: x + 1, lambda x: x * 2], whose lambdas capture nothing.
The census has no closure refusal; the programs A184 looked at used module functions and lambdas bound to names.
The p2w programs need annotations as well: def make_adder(x: int): has no return annotation, and the harvest's annotator declines a function returning a function. Under A180 the corpus copy is annotated by hand as mypy --strict needs it (-> Callable[[int], int]), which is corpus work and outside this ADR.
Decision¶
-
A closure is a counted object. A function value points at a heap object whose header is an instance's (ADR 0024: a reference count, a descriptor, a class number) and whose payload is the function's address followed by one slot per capture. The class is synthesized, one per nested function that is used as a value. The class's descriptor names what releasing each capture owes (
sfor astr,lfor a list,ofor an instance,-for a scalar), so the release walk ADR 0024 already runs frees a closure and its captures with no new runtime helper. A closure is owned and moved by the slot rule like any counted value. -
Calling through a value passes the closure. The lifted function of a capturing
deftakes the closure as a leading parameter and reads the captures from it. A call through a function value loads the address from the object and calls it with the object first, then the arguments. A direct call of a nesteddefstays what ADR 0010 makes it, the captures passed as parameters, so code that uses no function value is unchanged. -
A function with nothing to capture is a closure of one slot. A module-level function, or a nested one that captures nothing, used as a value is a closure whose only slot is the code: a thunk, one per function, that drops the closure parameter and calls the function. The closure is built where the function is taken, a counted allocation like any construction. ADR 0070's
FuncAddrnow takes the address of that code, and__pp_closure_newbuilds the object around it. EveryCallablevalue then has one representation and one calling convention. The design accepted on 2026-11-14 emitted this closure once as static data with an immortal count. A library has no module-level data for it; the retention counter would also read an immortal object as live. So the closure is built where it is taken. A static closure waits for a measured cost. -
Capture by value where Python's cell cannot be told apart, a cell where it can. A captured name that neither function rebinds after the closure is made is copied into the closure when it is made, as ADR 0010 copies it into a parameter: a cell and a copy hold the same value for the closure's whole life. A name the nested function writes with
nonlocal, or that the enclosing function binds again after thedef, is a cell: a counted one-slot object the enclosing function allocates where the name is first bound and reads and writes through, and that each closure capturing it holds a reference to. That is what CPython does:make_countercounts. A closure made in each iteration of a loop sees the variable's last value. A cell is a synthesized one-field class as well, released by the same walk. A rewrite of the tree makes it explicit before anything reads it (frontend/cells.py): the variable's first binding constructs the cell. Every other read and write, in the enclosing function and in each nested one that refers to it, becomes a read or a write of the cell's field. It is taken where it is exact, and otherwise thenonlocalis refused: the first binding is a parameter, or an assignment at the top of the body, before any use, of a literal, a parameter or an annotated value; every later binding is=or an augmented assignment. -
Where a closure can be is where ADR 0070 puts a function value (a parameter, a local, a return), and also a list element, so that
ops: list[Callable[[int], int]] = [...]lowers; the list's element kind iso. A field, a dict or set member, a tuple component, a union case and a module-level global stay refused, each with its diagnostic, until a program asks. A closure is not printed, compared or hashed, as a function value is not (ADR 0070 §2). A lambda written in a list annotatedlist[Callable[[A], R]]is the nesteddefit means, typed by the element type and made just before the list, in a function or at a script's top level. Over a list of functions,print,in,index,count,remove,sorted,min,maxandsumare refused: CPython prints a function as<function f at 0x...>and compares one by identity. Here a function taken twice makes a new closure each time, where CPython has one object. -
pygo keeps its rule. A function spawned as a task still captures only what D15 lets cross a task boundary, by value, at the spawn site; a cell is not sendable, so a spawned function that would need one is refused there.
-
Cycles. A closure stored into a cell it captures, or into a list it captures, closes a cycle, which leaks and is reported as any cycle is (ADR 0024). No corpus program makes one.
Alternatives¶
- A two-word value, an address and an environment pointer. It keeps ADR 0070's address as is and adds an environment that is null for a function without captures. A function value then takes twice the slots, the registers and the list words, and the environment still needs the counted object and the calling convention of §1 and §2. One pointer to an object costs one load per indirect call, against which the pair saves nothing it does not pay for elsewhere.
- Cells everywhere, every captured name boxed as CPython does. It is the simplest rule and the slowest: every read of a captured
intin the enclosing function goes through memory. The by-value copy of §4 is exact where it applies, which covers each closure the corpora return exceptmake_counter. - Refusing
nonlocaland doing returns only. It takes three of the five programs and leavesglobal_nonlocalandscope, which are mostlynonlocal; the cell costs one synthesized class and the reads and writes through it.
Consequences¶
- A program that uses no function value emits the IR it does today. A program with ADR 0070's function values changes representation:
__pp_closure_newbuilds a closure around eachFuncAddr. An indirect call loads the address from that closure. The verifier'sIR20checks the call against the closure's signature as it checks the address today. - With the p2w copies annotated,
closures_nested,chained_calls,lambda,global_nonlocalandscopemeet no closure refusal; each still has to pass the rest of the program. - The retention counter counts closures and cells with the instances, so a leaked closure shows as
POST-INST live != 0, andmake asancovers an over-release. - Decided by the owner on 2026-11-14 (A196): the counted object of §1 over the address-and-environment pair, a cell only where a copy differs from Python's (§4), and a list element in this step (§5). A cell is not sendable, so a spawned function that needs one is refused at the spawn site (§6).