ADR 0058: Tuples as values¶
Status: Final Type: Feature Created: 2026-10-08 Amends: 0045 (phase 2, and the return tier widened to any component); 0030 (a tuple of ints, bools and strs is a key and a set element) Related-ADRs: 0045 (the three tiers this completes as phase 2), 0057 (the argument that admits a nested value), 0035 (a field read takes its slot index at run time), 0027 and 0028 (the list forms a tuple operation rewrites to), 0030 (key kinds, and the set order nothing may observe), 0024 (what a counted component costs), 0066 (an optional component)
Context¶
ADR 0045 serves tuples in three tiers. A tuple that is only taken apart never exists: t = (x, y) writes hidden slots recorded on the name, called a pack, and unpacking, a literal index and len read them. A tuple that lives in a list is a compiler-synthesized class with one field per component, reference-counted, released and printed by the class machinery. A -> tuple[...] return crosses in the per-task slots, and only an int, float, bool or str component may. Everything else was refused under the name "phase 2": a pack used as a value (print(t), sorted(t), t1 + t2), a non-literal index, slicing, in, nested tuples, tuple(...), and comprehensions over enumerate and zip.
The p2w census of 2026-10-07 found phase 2 the largest remaining blocker that is not a recorded decision. Stripping the tuple-related lines from the blocked programs predicted that five would pass with a phase 2 (tuples.py, type_constructors.py, builtins_iteration_simple.py, builtins_iteration_tools.py, constructors_advanced.py). Every tuple in those programs has an arity known at compile time, and none is a dict key. The draft of 2026-10-08 recommended answers on that evidence.
The Shed Skin census of 2026-10-16 contradicts two of them. Tuples are the largest root there, 33 of 58 programs, and among the programs mypy accepts in strict mode, rubik2 is stopped by tuples alone and sudoku1 mostly by them. What the census programs write that the draft deferred or refused:
| need | programs | the code |
|---|---|---|
| a tuple of run-time length | rubik2, sudoku1, genetic2, chess | return tuple(self.state) declared -> tuple[int, ...]; puzzlebackup.append(tuple(puzzle[c])); tuple([TreeNode() for _ in range(n)]); tuple([i for i in range(128) if not i & 8]) |
| a tuple as a set element or dict key | rubik2, dijkstra2, sudoku5, sunfish | state_ids = set([current_id]) with in and add; self.vertices: dict[tuple[int, int], Vertex]; dict[tuple[str, tuple[int, int]], ...] |
| a returned tuple holding a list or an instance, unpacked at the call | adatron, dijkstra2, genetic2, sat, sudoku2, pygmy | return alphas, bias then alphas, bias = train(...); return (finaldist, finalpath) then wt, nodes = bidirectional_dijkstra(...) |
The last row is the refusal "a tuple component crosses the per-task return slots, so it is one of int, float, bool, str": 15 sites in 9 programs. rubik2 needs the first two rows and nothing else.
Decision¶
A tuple's component types are always known at compile time; its arity is known at compile time unless it is written tuple[T, ...]. An operation on a fixed tuple whose result has a static arity lowers by rewriting over the components; a tuple[T, ...] is an immutable list. The representations are three: a pack, the synthesized class, and, for tuple[T, ...], the list runtime.
- A pack becomes a value where a value is needed.
print(t),repr(t), an argument, a list element, a field or a returned value reads the hidden slots and builds the heap tuple at that point, through the construction tier 2 already has. Tuples are immutable and their components are values, so building at the use cannot be told apart from building at the binding. - Operations with a static result are compile-time rewrites over the components: literal slices (
t[1:4],t[::-1]),t1 + t2,t * 3,len, truth (the arity),x in t(anorof==over the components, where a component whose type==can never match folds toFalse, as CPython's==answers),==,!=and the lexicographic<,<=,>,>=.sorted(t),list(t),min,maxandsumare the same calls over the list literal of the components, so they take a uniform tuple, as they take a list. Starred unpacking of a tuple, andtuple(x)of a literal list, astrliteral, a tuple, or arangewith literal bounds, are rewrites too. Each rewrite lowers through the existing==,<and list lowerings over component reads, never through a second copy of the comparison rules. - A non-literal index on a uniform tuple (
t[i], all components of one type) is a bounds check raising CPython'sIndexError("tuple index out of range")and one field read: a field getter takes its slot index at run time (0035). On a mixed tuple it stays refused, because the result has no single type. - A component may be a scalar, another tuple, or any counted value (a list, dict, set, instance or union). A nested tuple is bounded by the nesting its type writes (0057's argument). A tuple holding a mutable value can take part in a reference cycle; it follows the instance's policy of 0024, which leaks a cycle and reports it at exit (A173). A counted component's member types (a list's element, a dict's key and value, a set's element, a union's cases) are part of the tuple's shape, so
tuple[list[int], int]andtuple[list[str], int]are two types. A literal where a tuple is declared fills each counted component from the declared type; a scalar component is lowered as written, so an int where a float is declared is refused, as CPython keeps it an int. - The iteration forms: tier 1's desugars extend to comprehensions with tuple targets and over
enumerate/zip, nested targets (for i, (a, b) in ...),enumerate/zipover astror a literal,start=as a keyword, anddict(zip(keys, values)). A tuple target other than names (self.w, self.h = w, h, the swapu[i], u[j] = u[j], u[i]) evaluates the right-hand side, then stores each target left to right, so each target's subexpressions run at its store as in CPython.reversed(x)becomes an iterable anywhere, as a reversed copy.list(enumerate([]))of an empty literal is an empty list, as[]is. - A tuple parameter:
def f(p: tuple[int, int])takes the heap tuple, borrowed as an instance parameter is; a default, an annotated local and an annotated field take the same type. The argument must have the declared shape, so(0, 0)wheretuple[float, float]is declared is refused: CPython keeps the ints and prints(0, 0). - A returned tuple may hold any value a function may return, a list, dict, set, instance, optional or union included. When every call takes it apart at once (
a, b = f()) or binds it to a name only unpacked and indexed by literals, each component moves through a per-task return slot, an owned counted pointer as astralready is. No tuple is allocated. A call used whole builds the heap tuple with the callee's member types; a boxed union is refused there, since no return slot holds one. The 8-component width of the slot array stays. - A tuple may be a dict key or a set element when its components are int, bool, str or such tuples, nested, in either representation. The runtime holds one hash and one ordering over a tuple, written once as C walking the class's slot descriptor (0035) or the list's elements, as every runtime helper is; equality is that ordering answering 0, and
sorted,sort(),min,max,in,indexandcountover a list of tuples use it too. The table's hash of a key is the runtime's own, mixed for its probing as every key's is (0030). No program can observe it: a dict iterates in insertion order whatever the hash, and a set shows this runtime's order (A179).hash(t)written in the program is CPython's value, a different function (0063). A key holding an instance, a list, a dict or a set stays refused (CPython raisesTypeError: unhashable typefor the mutable ones, and this compiler does not hash an instance item as a key). tuple[T, ...]is an immutable list. It is the list runtime under another type:tuple(xs)over a list, a slice or a comprehension builds one by copying, aslist(xs)does; indexing, slicing,len,in,count,index, iteration, unpacking,==and the orderings are the list's; there is no mutating method, since the type has none to call. It prints with parentheses, and a one-element tuple prints(x,), through a second printing path beside the list's. A fixed tuple goes where atuple[T, ...]is expected (a-> tuple[int, ...]returning(1, 2)) by building the list form from its components, as mypy accepts; the reverse is refused, as mypy refuses it. The elements are int, float, bool, str and fixed tuples of those, although a list may hold more. Atuple[T, ...]and a fixed tuple compare equal when CPython says they do, which is component by component. It may be a dict key and a set element under item 8's rule.
A float component. CPython compares tuple components with identity tried before ==, so a NaN decides by which float objects are the same object. Without a NaN, identity and == agree. So sorting, min, max and the list searches over tuples holding a float go through the runtime's tuple comparison. It compares a float as a double and stops the program, naming the reason, at the first NaN on either side (A182). A float tuple stays refused as a dict key or a set element, since equal floats such as 0.0 and -0.0 must hash alike and the key hash walks the bits, and in ==, < and in lowered as inline comparisons, which would need the same stop in generated code.
A list component whose elements the runtime's list comparison orders (ints, bools, strs or key tuples, no float) is ordered and matched lexicographically by sorted, sort(), min, max and the list searches, as CPython's tuple comparison compares the lists.
Refused, by name¶
- An arity that depends on a run-time value in a fixed tuple: slice bounds that are not literals,
t * nwith a non-literaln. A program that wants either writestuple[T, ...]. - A non-literal index on a mixed tuple.
- A tuple holding a float, an instance or a mutable container as a dict key or a set element (item 8, and the float rule above).
==, the orderings andinlowered inline over tuples holding a float.- A boxed union in a returned tuple used whole (item 7).
- A tuple across a pygo task boundary (pygo D15 admits immutable values, and a tuple of scalars is one, but the boundary copies only those it names).
t is u, asisis refused for every type except inx is None(0038, A58).
Consequences¶
- Three of the five p2w programs predicted to pass did;
builtins_iteration_simple.pyandbuiltins_iteration_tools.pywere then stopped by other roots (an empty list with no use that types it, and astrstored where a list was declared). - In the Shed Skin census rubik2 compiles and matches CPython on three backends, and the tuples root shrank from 33 programs to 16. sudoku1 and genetic were left with other roots (
hash(), then integers wider than 64 bits). - Items 1 to 6 add no IR instruction, runtime helper or backend line: they reuse tier 2's construction, field reads and release walk, and frontend rewrites into lowerings that exist. Item 7 widens the slot wires to counted pointers. Item 8 adds the tuple hash and ordering helpers, and item 9 a printing helper and a type over the list runtime; each is written once in the runtime package and linked by the backends.
- The refusals change subject. "A tuple as a value is phase 2" disappears; what stays refused names a run-time arity in a fixed tuple, a mixed tuple's index, an unhashable or float component in a key, or a float tuple compared inline, each with its reason.
Alternatives considered¶
- A native tuple value type, a dedicated IR node and runtime layout: rejected for 0045's reason, which still holds. The class machinery already provides layout, ownership, release and printing, and a second representation of a heterogeneous fixed product would be a second place for the memory model to be wrong.
tuple[T, ...]is homogeneous, which is why the list runtime can serve it. tuple[T, ...]deferred (the first draft's answer): rejected once the census showed four programs building one (rubik2, sudoku1, genetic2, chess). It costs a second printing path, and two internal types for what CPython calls one.- CPython's tuple hash as the table's key hash: rejected as unneeded, since the table's hash shows nowhere a program can see;
hash(t)itself returns CPython's value (0063). - A heap tuple refusing a mutable component (the first decision): replaced by A173, since an instance cycle was already possible and seven census programs build such tuples.
- Every pack on the heap from its binding: rejected for now. It would cost an allocation per tuple that is only taken apart, which tier 1 exists to avoid; a pack used as a value allocates at each use, which is measured before anything replaces it.