Skip to content

ADR 0029: Closed tagged unions, with match as the eliminator

Status: Final Type: Feature Created: 2026-07-30 Consolidated: 2026-08-07: takes in the union-case clauses of 0034 (an instance as a case; the case Item() as it: spelling), retired into 0024 Amended-By: 0065 (A161: the classes a union names are one case), 0066 (A164: a union of None and one pointer-held case is that pointer) Related-ADRs: 0026 (the slot rule this extends to a fourth counted type, and the borrow classification), 0024 (the heap memory model; the cascade refusals), 0013 (match over select, and why the eliminators stay separate), 0038 (guard-position narrowing over these unions), 0041 (the member types of a container case), 0007 (the propagation path the NULL tag serves), 0031 (which reuses the hint-threading arrangement established here). Provenance: arbitrations A79–A82, A150, A154, A171, A174; settles A10 for POST-shaped code, sharpens A13 without deciding it, records A41 as not collapsed.

Context

A union type (int | None, int | str) needs three decisions: how a union value is represented, how a value gets into a union (introduction), and how a program reads it back out (elimination). Elimination was the real decision. At the time, no Python spelling for reading a union back was accepted: x is None (A58), isinstance(x, int) (PP502), and match existed only over select. Which one gets unrefused determines how much of the feature exists: is None buys Optional and nothing else, isinstance buys binary sums, match buys the general form.

Decision

Representation

A union value is a pointer to a heap box: a reference count, a tag, and one eight-byte payload. A union of None and one case held as a pointer is that pointer, null for None, with no box (0066).

The tag is the case's type. Cases of one union have distinct types by construction (a union of a type with itself is that type), so no discriminant beyond the payload's kind is needed. Everything below follows from this one sentence: it is why the eliminator matches type patterns, why exhaustiveness is decidable by counting types, and why select's sum does not collapse into this one (see Alternatives).

Reading the tag of a NULL box gives −1. That lets a union-returning function raise: the placeholder the propagation path (0007) returns matches no case.

Introduction is widening, and widening is not conversion

A return 5 inside -> int | str tags the value implicitly, at return, at an assignment, at a call argument. This keeps it clear of the no-implicit-conversion rule (A14): conversion changes a value's representation behind the author's back, where widening changes no bits; it records which case the value is in. 5 is still 5.

Widening chooses a case by the value's type; the case the value would merely fit never decides it. A union's case is observable (the eliminator can ask the tag), where a plain slot's promotion is not: nothing in the language can ask a float what it used to be. CPython never promotes anything, so the object return 5 produces inside -> float | None is still an int, and case float(v): does not fire; choosing the Float64 case would make the compiled program take a branch the interpreted one does not.

So -> float | None refuses an int where -> float accepts one. The asymmetry is the correct answer: the slots differ in the property that observes the promotion. The same fact refuses bool into an int case: CPython's case int(v): does match a True, and prints True where a widened box would print 1. A value no case can hold is refused with the conversion named (float(n)): writing the conversion out is the author choosing between answers, and inventing that choice for them is what the no-implicit-conversion rule forbids.

A case named twice is that case, as CPython's | reads it: Opt = str | None makes Opt | None the union str | None. A union that names one case only (int | int) is refused, asking for the type without the |.

A function whose return type admits None must say return None; falling off its end is refused, since mypy reports a missing return there for any return type but None and Any (A171).

Elimination is match, exhaustiveness-checked

A match over a union must have an arm for each case or a case _:; anything less is a diagnostic. Over -> int | None, the arms are case int(v): and case None:.

Every case clause must be a pattern CPython matches identically, because the interpreted run has to take the same branch (rule D1: the compiled program and the interpreted one are the same program). case None: is a singleton pattern; case int(v): is a class pattern over one of CPython's self-matching builtins (int, float, str, bytes, list, dict, set among them), so the positional capture binds the whole subject.

Three refusals at the case clause hold the exhaustiveness check up. Each closes a way the check could be made to prove something false:

  1. A guard is refused. case int(n) if n > 0: covers the Int64 case for some values, so counting it as covered would be a false proof.
  2. A clause naming a case the union does not have is refused. Interpreted, it is a branch that never fires, so accepting it would be exact. It is refused anyway: the exhaustiveness check would count a dead clause, letting a match claim coverage it does not have.
  3. A repeated clause is refused, for the same reason at one remove.

The check is over the declared cases of the subject's slot, so it is as good as that declaration; a union with a case list that cannot be resolved is refused at its annotation. match is a statement, so a program may still never match a value at all; exhaustiveness is a property of the match you wrote.

Lowering is a tag read and a comparison chain, the same shape a select's cases lower to. Each case's payload is read inside the block its tag comparison guards. The payload readers take the tag they were compiled for. A mismatch traps in both build modes: no POST program can cause it, so it is a compiler-bug check, kept because reading the wrong member is one pointer-shaped integer or one integer-shaped pointer.

0038 adds the eliminators harvested code writes for an optional: is None, guard clauses, assert, truth, and and or.

The instance case

An instance may be a union case (Item | None) under the object tag; release-by-tag reaches the instance release. The box owns the instance: widening takes a reference. The payload read back out is borrowed. These are the same sentences as for the Str case, with one type changed. Two rules come with it:

  • The classes a union names are one case, because the tag names a type and every instance has the same one; a method on that case dispatches on the class the instance holds (0065, A161).
  • case Item() as it: and not case Item(it):, decided by CPython. case int(n): binds because int is one of the self-matching builtins; their class pattern takes a positional sub-pattern meaning the whole subject. A POST class has no __match_args__, so case Item(it): raises TypeError: Item() accepts 0 positional sub-patterns (1 given) before any case runs. Accepting it would compile a program the interpreter refuses to start: rule D1 in the sharpest form, because the spellings differ for a reason invisible from the compiler's side.

Container and bytes cases

list[T], dict[K, V] and set[T] are union cases (A150), and so is bytes (A174), each under a tag of its own and released by tag. A case with an outgoing reference had been refused because release-by-tag would cascade, a recursion with no bound and a constructible cycle. The instance case answered that first: cascading frees drain the destruction queue of 0024, so the C depth is bounded whatever the graph. A cycle passes through an instance; it is leaked and reported at exit. A container adds nothing new. A144 asks for the rest: mypy accepts xs: list[int] | None = None, the idiom for an optional argument that would otherwise be a mutable default.

  1. One case per container kind. list[int] | list[str] is refused for the reason two instance tags would be: the tag names a kind and the element types are not in it (0041: dtype equality is not type equality), so a match could not tell them apart.
  2. The case's members travel with the union. A container case is a type minted with its element, key and value types. A union's cases are handed along with their members and compared with them, which is ADR 0041's boundary check with no new site: a list[int] cannot be widened into a list[Item] | None slot and read back as instances. A parameter and a return pass the members through, as a container does.
  3. case list(xs):, case dict(d):, case set(s): and case bytes(b): bind the whole subject, since these are self-matching builtins.
  4. copy.deepcopy copies a box's container payload rather than sharing the box.

What a union does

  • Truth: False for the None case, True for an instance (refused when the class defines __bool__ or __len__, which this compiler does not dispatch), the payload's truth otherwise: CPython's answer for each case this compiler lowers. if x: narrows as if x is not None: does, if not x: as if x is None: does, and while x: narrows the loop body.
  • x or d over a T | None, with d of type T, is a T: CPython returns x when it is true, which it can only be in that case, and d otherwise. An empty d takes the payload's members (route or []). u or v and u and v over two T | None, or a T beside a T | None, are the one T | None CPython returns, the payload boxed again where it needs to be. x and d with a plain d stays refused in a value position, since it can return None.
  • print of a union writes each case as its value would be written, and None for the None case.
  • d.get(k) is a V | None: the hit is widened into the V case and the miss is the None case.
  • A bare None is a compile-time constant where CPython's answer is fixed: print(None), str/repr/bool of it, not None, f"{None}", and None compared with itself or with a value of a type with no None case. It is refused wherever it would need a slot, since only a union holds it.
  • for c in u over a union whose cases all iterate to one element type (list[str] | str) is a branch per case on the tag, each running that case's own loop, with the loop's break and else. The list case is retained for the loop, as CPython's iterator holds the list. list(u) of a binary union of iterables (bytes | list[int]) branches the same way.
  • A union is a list element (A154): list[T | None], and list[A | B] over any union this ADR lowers. The list runtime releases a box by kind, so the cascade and the cycle are answered as for a field. A box is immutable once built, so [None] * n shares one box across the positions. A name bound from xs[i] narrows as any local does, and xs[i] is None is a tag test; xs[i].v is not narrowed, since anything between the test and the use may store into the list.

Ownership: release by tag, in exactly one place

The slot rule (0026) is unchanged: every reference a frame holds lives in a slot, every slot owns exactly one reference, and the release epilogue is appended to every returning block. A union box joins it as a row in the same table. The new part is the box's release, which releases the payload when the tag names a counted case.

This is the first release in the compiler conditional on a value only the run time knows. An instance releases the fields the class statically has. A list releases by a property of the container fixed when it was made. A union releases the payload if this box, on this run, is in a counted case. The branch lives in one place, so there is one site that can be wrong. Around it sits the standing discipline. The constructors take a reference (the box owns the payload). The payload readers borrow (classifying them as owning would free a string the box still points at, then free it again at the box's release). Every union-typed expression result is parked in a frame slot at the static build site, so a widening inside a loop reuses one slot and releases the previous iteration's box on the next.

Refused, by name

  • More than two cases (A79): the tag is a word, so the limit is scope.
  • Any and object: the open union (A13), deferred; the closed half is answered here, so what remains of A13 is the open case.
  • A channel or another union as a case. A heap tuple is a case beside None (0066), and refused beside a class or a second tuple.
  • A narrower scalar (Int32 | None): the payload is one eight-byte slot, and widening the element would silently change the program's layout, the same argument as Chan[T] and list[T].
  • int | bool: bool is a subclass of int, so case int(n): matches the bool case too and the answer would depend on the order the arms were written. The eliminator has to agree with the interpreter (rule D1), and here it cannot.
  • Optional[T] and Union[A, B]: refused with A | B named. Optional[int] needs from typing import Optional and int | None needs nothing, so the spelling this compiler lowers is the one an unmodified CPython run already has.
  • A union at a task boundary: the retention counters are per task (A69), so a copy would put a box's allocation and the release in different tasks and no per-task counter could balance.
  • A for over a union whose cases iterate to different types (list[int] | str) or that has a None case.
  • Over a list of unions: print(xs), sorted, min, max and sum (None has no ordering and no addition; CPython raises TypeError once one meets another element), xs.sort(), and in, index, count and remove with a bare case on the left.
  • A match over anything else: a scalar, a Str, a container. Spec §5.1 permits them; the type that needed an eliminator is the one that has it; the refusal names the subjects that lower.

Consequences

  • X | None compiles with stdout byte-identical to CPython's on every backend, the shape Optional-returning functions were blocked on.
  • The eliminator first served code written in POST's own idiom only. Harvested Python overwhelmingly eliminates optionals with is None, truthiness or assert, which this ADR left refused (A58, A82 records the cost); 0038 and the truth of a union above later admitted them. This answers A10 for POST-shaped code.
  • Every introduction into a boxed union allocates a box, including None. An immortal None singleton (rc == -1, the sentinel a Str literal already uses) is the named successor for the hot path; it was not taken here because an immortal box makes the live and allocated counters asymmetric. Those counters agreeing was the acceptance evidence for the memory model. 0066 removed the box for an optional of a pointer type.
  • The exactness rule cost one shipped-and-removed divergence to learn: widening briefly chose the case a value would fit, and only a CPython differential that actually reads the tag back can see that class of bug: a test of introduction that never runs the elimination is a test of half a round trip (notes/accept-then-wrong.md §28).
  • print of a union with a container case that holds instances is refused, and is owed.

Alternatives considered

  • is None or isinstance as the eliminator: rejected. is None buys Optional and nothing else; isinstance buys binary sums. match buys the general form, spec §5.1 permits it explicitly over scalar and aggregate types, it was already half-built for select's arms. It is also the only spelling that is exhaustiveness-checkable, so the compiler can prove every case is handled.
  • Collapsing select's sum into this union (A41): rejected, for a reason that is a finding. select's sum is tagged by a case key; this union is tagged by a type. These are different discriminants, and only one is derivable from the value. select(a=c1.recv, b=c2.recv) over Chan[int] operands has the type tag int on both arms and the key is gone: a tag that recovers "a" from "b" has to be a label the program chose, which is a named-variant sum (Msg(str) | Sig(bool)). That is a different feature. The counter-example (two channels of one element type) was in the corpus before the expectation was written. select also returns a pair, which needs an aggregate besides. The match statement therefore dispatches on what the subject is: a select call to the key-tagged parser (0013), a union to the type-tagged one; folding the parsers together would make the wrong eliminator reachable from the wrong subject.
  • Only list as a container case, which covered 17 of the 20 census sites (the other 3 were dict): rejected (A150), since dict and set cost a tag and a release line each and the members rule is the same for each.