ADR 0045: Tuples¶
Status: Final Type: Feature Created: 2026-08-04 Consolidated: 2026-08-07, absorbing 0046, 0048, 0049, 0050 (retired) Amended-By: 0058 (tuples as values, and a returned tuple's components widened to any returnable value) Related-ADRs: 0011 (the per-task slot mechanism), 0013/0030 (the recognise-the-consuming-statement pattern), 0023/0024/0035/0036 (the class machinery the heap tier reuses), 0031 (annotation-in-scope), 0044 (the slices the star lowers into). Provenance: arbitrations A131–A139.
Context¶
POST Python has no general tuple type, yet Python programs lean on tuples constantly. Most uses construct a tuple and immediately take it apart (parallel assignment, divmod, for k, v in d.items()). Fewer keep a tuple on the heap (an element of a list, an annotated parameter), and returns form a third group. One decision covers all three, in tiers: each tier engages heavier machinery only where the lighter one cannot express the program, and anything outside the tiers refuses with the reason named.
Decision¶
Tier 1: value-free forms, where a tuple that is only ever taken apart never exists¶
Where a tuple is constructed and consumed in the same statement shape, the consuming statement is lowered and no tuple value is ever built:
- Parallel assignment
a, b = x, y: the right-hand side is parked in hidden temporaries before any store. A Name's Value is its slot, so direct stores would corrupt the swap. - Packs:
t = (x, y)writes compiler-named slots recorded on the name. The slots are real, so ownership follows the ordinary slot discipline and rebinding a source name cannot reach inside a pack. They are shared across all packs of the name, which makes a conditional pack flow-correct, so a re-pack that changes a component's type is refused and never versioned into flow-blind storage. A name holds its tuple one way for the whole function, chosen from all its bindings, read off astero's binding positions: a name that only a pack,divmodor a-> tuple[...]call binds keeps the hidden slots; a name also bound any other way (a loop target, an unpacking, a subscript read, an optional, a parameter) holds a heap tuple in its own slot at every binding, the pack's included. A choice made at the first binding in source order would let a path that skipped a branch read slots nothing wrote. A tuple name given aT | Noneis refused with PP410, as mypy refuses it, since the first binding types the name. - Reads:
a, b = t, literal-indext[k](a static out-of-range index is CPython's IndexError, at compile time), andlen(t)as the arity constant. divmod: operands are parked once, then//and%are lowered from synthetic reads, so the zero-divisor raise and the floor rules stay the operator lowerings' own.- Desugars:
for k, v in d.items():becomesfor k in d:withv = d[k]prepended;enumerateandzipbecome hidden-counter range loops that inheritbreak/elsewhole. - Starred forms: in
first, *rest = xsover a list, before-star names are literal subscripts, the star is a slice, and after-star names are negative literal subscripts;[*a, x, *b]is a leading literal (or slice copy) plus an append loop, whose member check is the type agreement; an unpack head may be an arbitrary expression, parked once in a hidden slot before the loop, which is CPython's own iterator-creation order.
The arity guard is the semantic content. A naive t[0] desugar raises IndexError on a short list where CPython raises ValueError. A guarded unpack therefore synthesizes ordinary source, if len(t) < M: raise ValueError(f"…"), so the comparison, the raise, and the message bytes are the existing lowerings' own. The three messages are byte-for-byte CPython's:
not enough values to unpack (expected at least M, got N): starred form, with the runtime length;not enough values to unpack (expected N, got M): plain form;too many values to unpack (expected N): plain form, without a count.
Plain unpack also accepts a list, a bytes or a str value on the right (region, product, qty = line.split(","), a, b = data[p:p + 2]). The value is parked once and guarded by the two plain-form messages. Each target is then bound by an index, which reads an int from a bytes and a one-character str from a str, the items CPython's iteration gives.
Tier 2: the heap tuple is a class without a name¶
A class instance already represents a heterogeneous fixed product, with refcounting, a release walk, boundary member checks and a print path. A heap tuple is therefore a compiler-synthesized ClassInfo, one per component signature, with fields f0…fn−1, registered in the same class table as source classes. The slot descriptor, the release walk, the member check and the instance-dtype gates follow without new mechanism. No backend needs a tuple-shaped line.
No functions are synthesized: construction is an inline object allocation plus one field store per component, with the retain parked in the construction node's slot (0027's literal-in-a-loop discipline). Printing is a frontend-emitted arm ((, per-component helpers with repr for Str, the one-element trailing comma, )) and no __repr__ is synthesized.
A component may be any value 0058 admits. Three forms produce heap tuples here: a tuple literal as a list element; list(zip(...)) over two to eight lists, stopping at the shortest; and list(enumerate(x[, start])). Consumers: unpack, literal and negative-literal indexing (including nested pairs[i][j]), len, for-unpack, and isinstance(t, tuple).
Annotations: list[tuple[...]] resolves to the synthesized class wherever an annotation resolves: a parameter, a declared return, an annotated binding (0031's rule reaching tuple elements). This covers the empty-list initializer, .append, indexing, len and for-unpack downstream of the type. A tuple holding a container or an instance follows the instance's cycle policy (0058, A173).
An instance dtype is identity-bearing, so the typechecker must never mint one. It takes an optional resolver parameter that the frontend binds to the sole creator-and-registrar of tuple classes; the component vocabulary is one shared authority consulted by both sides. A resolution site that does not pass the resolver (a cast above all) keeps its refusal.
Tier 3: returns cross in the per-task slots, not the ABI¶
A -> tuple[...] return reuses the per-task slot mechanism of 0011: the callee writes the components into per-task thread-local arrays and returns nothing; the caller drains them into its own slots immediately after the call and the exception check. Reentrancy is the same argument as the exception slot's: calls are LIFO and the drain completes before any other call can write. The arity is at most 8. A counted component (a Str first, any counted value since 0058) crosses by retain-in-callee, adopt-in-caller; dropping the retain would balance both counters while the caller reads freed memory. A call used whole builds the heap tuple (0058). The slots are a memory hazard first: a value left in them that nothing drains is a leak. A fall-off-the-end path in the callee would let the caller drain a previous call's leavings, so it is refused.
Refused, by name¶
Tuples as values, with their operations, are 0058's. These stay refused here: a non-literal index on a tuple whose components differ in type (it has no single result type, with the same sentence for packs and heap tuples), and *args in a signature, since a silently flattened signature is a different function. A starred target over a right-hand side with no length to guard is refused.
Consequences¶
- Most tuple code compiles with no allocation at all; only tuples that genuinely live in containers or annotations pay the heap price, and returns pay neither heap nor ABI.
- The three tiers cost the backends nothing: tier 1 is frontend rewriting, tier 2 reuses the class machinery whole, tier 3 reuses the exception-slot mechanism. A new backend inherits all three by implementing none of them.
- The refusal set is the contract: a form outside the tiers names what it is waiting for. The compiler's answers stay byte-identical to CPython's on everything it accepts, including which exception class a mis-sized unpack raises.
Alternatives considered¶
- A native tuple value type (dedicated IR node and runtime representation): rejected. The class machinery already provides layout, ownership, release and printing; a second representation of "heterogeneous fixed product" would be a second place for the memory model to be wrong.
- An out-parameter ABI for tuple returns: priced and rejected. It would have touched all backends, where the per-task slot mechanism already existed and touched none. (The original phase pricing said otherwise; the correction is recorded in
notes/accept-then-wrong.md§40.) - Refusing tuples until a complete tuple type existed: rejected. The corpus census showed construct-and-take-apart dominates real programs by an order of magnitude; serving those forms value-free delivers most of the surface with none of the representation questions.