Skip to content

ADR 0028: The aggregate surface

Status: Final Type: Feature Created: 2026-07-30 Consolidated: 2026-08-07: absorbs 0047 (constructor desugars; retired) and the generator-expression half of 0039 Related-ADRs: 0027 (what a list is; this ADR covers what you can say about one), 0030, 0044, 0029, 0064 and 0072 (generators). Provenance: arbitrations A1, A9, A12, A67, A72, A74, A83, A117, A133, A159, A179.

Context

Once containers exist, a dozen positions ask the same question (printing, truthiness, reducers, comprehensions, constructor calls). Each is a place where a check written for one representation silently misses the next. This ADR decides the shared predicate first, then the surface: how an aggregate prints, how one is built from another, how one is reduced.

Decision

The predicate: is_aggregate, aggregate-by-default

Checks ask one question, "does this value hold elements?", and the predicate ORs the two container shapes once (an Array[T] is a layout; a list[T] is an object). Three properties together keep a future representation from slipping past; any two leave a door:

  1. It is a property: a guard reading is_aggregate has no representation left in it to name.
  2. The dtype half is aggregate-by-default: the scalar and handle kinds are enumerated; everything else is an aggregate. A new container therefore refuses everywhere on the day the class is written, before anyone edits a check. The unknown answers "no", the same failure direction the promotion and cast paths use.
  3. A structural test forbids silent reliance on the default: every dtype the compiler knows must be classified scalar, handle, or declared aggregate, with the enumeration derived from the class tree itself.

Printing an aggregate

print(xs) writes repr of each element, because that is what CPython writes (print("a") is a; print(["a"]) is ['a']). String-element repr is decided on an ASCII domain, exact inside it, trapping outside: Unicode printability below U+0080 is 0x20–0x7E, so no table ships. The escape rule is CPython's in full: \t \n \r, \xNN in lowercase hex for other control bytes and 0x7F, doubled backslash, and the quote chosen ' unless the string contains ' and no ". A byte ≥ 0x80 traps at the first offending byte, naming it. This is a runtime trap because ASCII-ness is a runtime property; the alternative is a wrong escape on some input.

The lowering is an IR loop over the existing per-element helpers. A runtime __pp_list_print in the list unit would make list-using programs link symbols only print-using programs need. A program with a list and no print would then die at link with no output for any differential to compare. Array[T] printing refuses on separate grounds: an array element may be a narrow width whose CPython repr is the repr of the widened value (the standing Float32 formatting question).

A container's text as a str: str(xs), repr(xs), f"{xs}" and "..." + str(xs) of a list, a dict or a set are what CPython defines, over the container already lowered: "[" + ", ".join([repr(m) for m in xs]) + "]" and its {k!r}: {v!r} form for a dict, in insertion order. Each member is repr's question, so a list of lists recurses, an instance needs its __repr__ or the default of 0040, and a non-ASCII str stops as print does (A12). A set shows this runtime's order (A179, 0030).

Comprehensions

Comprehensions desugar to an ordinary for loop; [f(x) for x in it] is the model case. The loop lowerings that already exist take it (range, list and array iteration, filters as ifs), and the evaluation order is CPython's. The iteration variable is renamed to a fresh compiler-owned name substituted through the element and filters. Python 3 confines the variable to the comprehension. A shared slot would be wrong three ways at once: the variable leaks out; an enclosing binding is silently overwritten (the killer case, x = 99; [x*2 for x in r] then print(x) printing 2); a type collision refuses a valid program. The rename fixes all three with no scope machinery.

The list must exist before the loop appends, yet the element type is unknown until the element expression is lowered. The circle is broken by emitting the element kind as a constant and patching that one constant after the body lowers; lowering the element twice would have to be undone across six kinds of frontend state.

Several for clauses are nested loops, outermost first; each clause's names are renamed in the element, in that clause's filters, and in every later clause's iterable and filters. A tuple target (for k, v in d.items(), enumerate, zip) renames each name and is unpacked by the for the comprehension becomes. A tuple element is a heap tuple, as in a list literal. A dict or set comprehension is the same loop with another sink: the result is allocated before the loop with patchable member flags. The sink stores through the dict's put or the set's add, so a comprehension accepts what the matching literal accepts. A dict comprehension evaluates each key before its value, as CPython has since 3.8 (PEP 572).

Generator expressions

A consumer of a generator expression, such as sum(i.value() for i in items) or min/max/sorted over one, lowers by rewriting the genexp to the list comprehension that already lowers, through the single chokepoint the reducers share. The materialisation diverges from CPython in space only: the output is the same, since the reducers consume the whole sequence in order. It is visible: the list-allocation counter counts each one. The allocation-free accumulator lowering is priced (it needs a patchable slot dtype, beyond a patchable constant) and waits for a measurement that asks. A generator function is 0064's and 0072's.

any and all never materialise, because short-circuiting is observable: any(1 // x > 0 for x in [1, 0]) never divides by zero interpreted, while a materialised list does. They are a short-circuit loop (A133): a flag set to the empty answer, and a break at the first deciding element, out of every clause's loop.

map(f, xs) and filter(f, xs), handed to list, sorted, min, max, sum, set, any, all or join, are the generators (f(v) for v in xs) and (v for v in xs if f(v)); filter(None, xs) tests v itself. f is a function, a class, a builtin or a lambda written in place. CPython calls f on each element in order, as the generator does. The raiser walk counts f as called.

Iteration

for c in s walks a str by code point and for x in b a bytes as ints. for x in reversed(xs) is CPython's reverse iterator over a list, an index against the list's current length; over a str, a tuple literal or a range it is the reversed slice, which is exact there. for x in t over a tuple value walks its components in order when they share one type, the loop variable's; the components are read before the body runs, which is CPython's sequence since a tuple cannot change.

Constructor calls over existing values are spellings

list(reversed(xs)) is xs[::-1]. list(range(...)) is a comprehension. list(genexp) is the rewrite above. list(xs) and friends are copies via the full slice; list(...) also takes a tuple literal, a str, a dict walk and a set, in this runtime's order. dict(a=1) and dict({...}, y=2) are dict literals in other clothes, and dict(X) over any expression giving a dict is X.copy(), X evaluated once. set(xs), set("abc"), set(range(n)), set(d) and set(E for ...) are the set comprehension over the same walk, one insertion per element, as CPython builds them; so is set(...) over any other expression giving a set, a dict or a list, evaluated once, since inserting a set's elements in any order gives the same set. dict((k, v) for ...), dict([(k, v) for ...]) and dict(zip(keys, values)) are {k: v for ...}: each pair is evaluated key first and inserted at once. Each arm rewrites the AST and re-enters the expression lowerer, with zero runtime, backend or IR lines.

The reducers

sum, min and max lower in the frontend as loops over the operators that already exist, so no C is written. They agree with the hand-written loop by construction: sum emits the same add (inheriting its overflow rule), min the same compare (inheriting CPython's first-minimal tie rule and NaN behaviour). Mixed-type min(1, 2.5) stays refused (CPython returns the winning argument object, so the result type is not a function of the argument types); a homogeneous list never raises that question.

  • min([]) raises a real, catchable ValueError with CPython's message. min(xs) is an expression that can leave an exception pending with no raise in sight, so it marks its function a raiser.
  • sum of a list[float] requires an explicit start: CPython's empty answer is the int 0, so a monomorphic float sum prints 0.0 where CPython prints 0 on one input. The compile-time refusal beats a runtime trap. The diagnostic teaches the portable spelling (sum(xs, 0.0)), which agrees with CPython, wherever the result goes (A195).
  • sorted is one runtime helper over the stable merge sort 0027 shares with list.sort; reverse=True is CPython's reverse, sort, reverse, so equal elements keep their order.
  • key= is decorate-sort (A159): the frontend computes [f(v) for v in xs] once per element and in order, which is when CPython calls the key, and one runtime helper, __pp_list_sort_by, sorts the positions by the keys and permutes the list's slots. sorted(xs, key=f) sorts a new list. xs.sort(key=f) sorts in place; CPython empties the list while the keys run, so it is refused when a key could see the list (a lambda naming a local of the caller, or a list of the element type reachable from an element's fields or from a module global). min(xs, key=f) and max(xs, key=f) fold over the keys with the strict comparison, returning the first winner. A key is a named function, a builtin or a lambda written in place (PP032 spares these, amending the spec's §5.2). min, max and reduce over a generator are refused, since CPython interleaves their steps with the key's calls.
  • functools.reduce(f, xs[, start]) is the left fold, raising CPython's TypeError over an empty iterable with no start. The accumulator keeps one type (an int, a float, a bool or a str), and a step that would change it is refused, since CPython's answer for an empty list would be the other type.
  • Over a set, whatever expression gives it, sorted, min, max and sum, with key= or without, go through list(s), and reduce folds in this runtime's order (0030, A179). Python leaves that order unspecified, so a float total may round differently from CPython's.
  • The reducers refuse Array[T]: a narrow-width sum diverges from CPython's arbitrary-precision int before either overflows.

Consequences

  • The sugar surface costs the backends nothing: everything here is frontend rewriting plus one runtime sort helper.
  • The diagnostics name the heterogeneity deferral as the blocker of container programs; sugar is never the cause.
  • The counters make the surface visible: the genexp materialisation and the producing helpers show in the allocation numbers. The list runtime's producer-classification check (owning vs borrowing, derived from the parsed C) exists because sorted was the first list producer that was not a constructor.

Alternatives considered

  • A runtime print helper per container: rejected for the linkage trap. A program with a list and no print must not link print symbols, since a build failure has no output for any check to compare.
  • A scope mechanism for comprehension variables: rejected; the rename achieves CPython's scoping with none.
  • Trapping on empty float sum: rejected; a compile-time diagnostic teaching sum(xs, 0.0) is strictly better feedback for the same program.
  • Materialise-then-reduce for any/all: rejected, because it changes which programs raise: observability of short-circuit is semantics.
  • A key compared inside the runtime, calling back into POST: rejected for decorate-sort, which needs no callback from C and calls the key in CPython's order.