ADR 0030: dict and set, and why one of them matches CPython's order and the other does not¶
Status: Final
Type: Feature
Created: 2026-07-30
Amends: 0007 and 0027 (IndexError and KeyError return to the vocabulary, and a list's out-of-range trap becomes an IndexError)
Amended-By: 0058 (a tuple of ints, bools and strs is a key and a set element), 0071 (a dict may have a default factory, which d[k] consults before raising), 0073 (a dict value may be a list or a set, and a deep copy copies a dict's values)
Related-ADRs: 0027 (the ownership discipline, extended here to the key and value positions and to an unordered table), 0026 (the provenance table), 0028 (repr of a Str on the ASCII domain), 0024 (the cascade and the cycle, under its "Release"), 0013 (the lower-the-consuming-statement pattern), 0007 (the error-return lowering the raise placement serves), 0045 (which lowered the tuple-shaped forms first refused here), 0015 (bytes members), 0031 (the empty container). Provenance: arbitrations A12, A13, A58, A69, A72, A73, A77, A83–A86, A157, A174, A179, A183.
Context¶
With list[T] landed (0027), dict[K, V] and set[T] are the next containers. Everything in this ADR follows from one asymmetry: CPython has guaranteed a dict's insertion order since 3.7 and gives no guarantee about a set's.
Decision¶
Two representations, and which order is a property of the value¶
dict[K, V] |
set[T] |
|
|---|---|---|
| representation | compact: a dense entries array in insertion order, plus a sparse index of open-addressed slots holding entry indices | a single open-addressed table of slots, linear probing |
| iteration order | insertion order: the only order the entries array has | slot order: a function of the hash and the capacity |
| is that order CPython's? | yes | no; Python does not specify it |
| how is its printed form tested? | byte for byte | by what Python specifies: a set's text as a set |
| ownership positions | two (key, value) | one |
The two differ because of the types. CPython's insertion-order guarantee makes a dict's order a property of the value: a program can observe it and a reader can rely on it; an implementation that lost it would be wrong. A set has no such guarantee. A set is an unordered collection by definition, so an implementation that reproduced CPython's slot order would be reproducing an artefact of CPython's table. set is therefore implemented with whatever table is efficient and does not match CPython's iteration order; where a program's output is set-shaped, the comparison is order-insensitive. This ADR is the first application of a general rule: before matching a printed form byte for byte, ask whether every property of that form is a property of the value. Where it is not, constrain the comparison and leave the implementation free. A discipline no test can fail is no discipline, so a test checks the order divergence directly while fixing no particular compiled order, which would pin an implementation detail the type does not have.
What shows a set's order lowers, in this runtime's order (A179: fidelity is to what Python specifies). list(s), tuple(s), str(s), repr(s), an f-string and a for over a set walk the table's order, and sorted, min, max and sum, with key= or without, and reduce over a set go through list(s). A differential over such output compares a set's text as a set and a list copied from one as a multiset. A float total summed in this order is one Python allows, and may round differently from CPython's, so a differential sums floats that add exactly. set.pop removes an element the table's layout chooses and is not lowered.
The hash is mixed, an engineering choice with a semantic consequence. Linear probing is cache-friendly and its failure mode is primary clustering, which a well-distributed hash prevents; CPython's identity hash for small integers (hash(i) is i) clusters under it. So a finaliser mixes every key's hash. The mixing is chosen for the probe strategy it serves; the different set order follows from it. A dict's order does not come from the hash at all: it comes from the entries array.
One translation unit for both types. The hash and key-equality helpers are shared; duplicating a hash function is how containers come to disagree about what a key is.
The member types¶
A key or a set element is a value with a hash and an equality. It may be an int, a bool, a float, a str, a bytes (A174), a tuple of ints, bools and strs (0058), or an instance. A bytes is hashed and compared by content, as a Str is. A value is any of those, or a list or a set (0073). A key is constrained by hashability and a value by storability, so the two sets are named apart even where they coincide.
An instance key or element hashes and compares by identity, CPython's object.__hash__ and object.__eq__, unless its class defines both __eq__ and __hash__ (0063, A168). A dataclass without them is refused there, since its generated __eq__ sets __hash__ to None. A dict of instances keeps its insertion order, so it iterates and prints as CPython's, through the class's __repr__. d[k].field reads through a dict as xs[i].field reads through a list.
One divergence comes from CPython. float("nan") is never equal to itself, so a NaN key can be inserted twice. CPython's dict tries identity before equality and so stores one; POST has no identity to try for a float, so it stores both. It is one input class wide, the same divergence the float list-membership helper has, at another container, and a named one (A192).
What lowers, by which rules¶
The literals, d[k], d[k] = v, k in d, len, iteration, get, pop, copy, update, setdefault and clear on a dict; add, remove, discard, in, len, iteration, copy, clear and the four combinations on a set; truth, printing, parameters and returns for both. These rules decide how:
- A literal evaluates in source order, one insertion per entry. An empty
{},dict()orset()takes its member types from its position (0031); Python has no empty-set literal. d[k]is one hash, one branch and one read, and raisesKeyErroron a miss (or consults the default factory of adefaultdict, 0071).k in dfollowed byd[k]would hash twice, a cost a reader would not expect from one subscript.d[k] = vnever raises.lenmust not fold, for 0027's reason unchanged: a container's length is a runtime value, so a compile-time constant would be silently wrong after the first store.- Iteration is a cursor answering the next live entry, so a hole left by
popadds no cost to the IR: the skipping is a single loop inside the runtime. - Changing a container while iterating it raises
RuntimeError; the alternative was a silently wrong walk. A growth compacts a dict's entries array and a rehash moves a set's slots, so a cursor taken before either indexes a different arrangement afterwards. The test is on the size, which is CPython's rule:d[k] = von a key already present leaves the size unchanged and does not raise there or here. The messages are CPython's byte for byte, capital S included:dictionary changed size during iterationandSet changed size during iteration. updatefollows CPython's merge: a key already present keeps the key and its position and takes the new value, retained before the old one is released, sod.update(d)leaves the dict unchanged. A copy keeps each entry's hash and the source's order.setdefault(k, v)isgetwith a store on the miss; the one-argument form would insertNone, so it stays refused.- Two sets combine (
|,&,-,^, andunion,intersection,differenceandsymmetric_differencewith one set argument) into a new set by one runtime walk, each element compared through its stored hash by the key's equality. A set of instances stays refused there, as doesset.update, which changes a set in place. - A reducer takes a dict walk.
sum,min,maxandsortedoverd.keys(),d.values()or the dict itself (the keys, as CPython walks it) are rewritten to the list comprehension that already lowers, through the chokepoint 0028 uses for a generator expression.sorted(d.items())is[(k, d[k]) for k in sorted(d)], withreverse=passed through; the rewrite is exact because a dict's keys are distinct, so comparing two entries never reads a value. Both apply to a dict reached by a name or a field chain, which reads the same each time the rewrite evaluates it. A dict any other expression gives (a call, a display) is evaluated once and its keys walked, and so is the dict of a view in one of these positions:sum(f().values())evaluatesf()once, where CPython does, and walks its values. f(**d):dmust be a localdict[str, V]spread once, after the other arguments. The explicit arguments are lowered first, thend's keys are bound as CPython binds them. A parameter left todreadsd["p"], or its default when the key is absent. Every failure is CPython'sTypeErrorwith CPython's message: a key an explicit keyword also gave, a key no parameter names or a positional argument filled (ind's order), then the required parameters still missing, named together. More than four required parameters left todare refused, and so is a dict display, a call or a second spread as the operand, since binding after the explicit arguments would reorder its evaluation.
Views¶
A view is a live window onto the dict. This compiler gives it no value of its own: a view is a reference to its dict plus a static choice of what it shows, keys, values or items. So d.keys(), d.values() and d.items() lower in a for header and in a reducer, following 0013's arrangement of lowering the consuming statement in place. A for header binds a view's dict to a hidden local when it is no name or field chain, as it binds a container the body may rebind, so for k, v in f().items() calls f once. A view held in a name (A183), keys = d.keys(), binds a hidden name to d itself. Each use of keys becomes .keys() of that hidden name. The view is live, as CPython's is, since the name holds the dict and no copy; rebinding d leaves the view on the dict it was taken from. The rewrite applies where each binding of the name is a view of one kind and the receiver is a dict reached by a name or a field chain, with no nested scope using the name. A use the rewrite missed would find no binding and be refused, so the dict is never mistaken for a view.
The positions a view is used in become what already lowers: len(v) is len(d), k in d.keys() is k in d, list(d.items()) is [(k, d[k]) for k in d], and print, str and an f-string show CPython's dict_keys([...]). Three uses stay refused, with one message that names what lowers: a compared view, in over values or items (which compare values with ==, a second rule), and a view a nested function uses.
What is refused, with a reason named for each refusal¶
- Heterogeneous keys or values:
dict[str, Any],dict[str, object],set[Any], a baredict/set, a mixed literal. All one standing deferral (heterogeneity), named in each message. - A dict value that is a dict or a tuple, which 0073 covers and has not built, and
==between dicts. frozenset: asetthat refuses mutators, so building it is pure work.- The method surface beyond the above.
fromkeysbuilds from an iterable;popitemreturns a pair; the set comparisons compare two whole sets;set.popis above. Each is refused with its group named. d[k]with a key whose type has no repr this compiler writes, since a missing key raisesKeyError(repr(k));d.get(k)andk in dlower for it.- A task boundary.
Chan[dict[…]]andChan[set[…]]are refused forlist's reason unchanged: the retention counters are per task, so a copy-on-send would put a container's allocation and release in different tasks and no per-task counter could balance across that.
Ownership: one code per position, and why that is not a bitmap¶
The rule. A dict entry owns one reference to its key and one to its value. An insertion takes a reference on a fresh key (an overwrite keeps the key it already owns, which is CPython's rule) and always on the value, releasing the old one it replaces. pop and the release walk release both. A set element slot owns one reference; add of a present element takes none.
Each position has an ownership code naming what it holds (none, a Str, an instance, a bytes, a list, a set), so a dict's release costs one branch per position, once, with no arity limit. An instance needs a bitmap because its fields are heterogeneous. A bitmap's width is an arity limit; a silently dropped mask bit is a use-after-free. A dict's codes are indexed by what the position means, so there is no third position to run out of bits for: a dict[str, str] of ten million entries needs no refusal. A single "holds a Str somewhere" flag would have made a dict[str, int] release its integer values as pointers; the codes are per position because the positions differ.
A hole is left where it is. pop releases the key and the value and marks the entry dead; the entries array is compacted at the next growth. Compacting on removal would be O(n) per removal and would move every later entry, whereas an entry's position is the insertion order this type promises.
pop's ownership order is the one thing here that is a use-after-free if written the obvious way. The delete releases both positions, so a value read before the delete must first be given a reference; reversed, pop returns a pointer the dict has just dropped the last reference to, which is correct at small sizes and fatal in a loop.
Provenance (0024's "Provenance", extended): the constructors are owning; the readers of a key or a value are borrowing, since the container holds the reference. The classification acts as a tripwire for the reason 0028's consequences give, unchanged: the frontend's default is owning, so a borrowing container-returning helper added later would be adopted and double-freed.
The cascade and the cycle of 0024's "Release" were first answered by admitting only members with no outgoing reference. Instances and containers as members answer them as a list of instances does: a release queues its work and does not recurse. A cycle through a container leaks and is reported at exit.
KeyError and IndexError join the vocabulary; the trap is retired¶
IndexError and KeyError left POST's exception vocabulary for different reasons and return for different reasons.
IndexError went because no POST construct raised one: an out-of-bounds index trapped, so it was a type with no use case behind it. 0027 gave the language a list, whose length is a runtime value, so an out-of-range index on one is a runtime condition like a division by zero, no longer a program a compiler could refuse.
KeyError went because it is the one builtin whose __str__ returns repr(args[0]) rather than the message, so str(KeyError("k")) is "'k'", and spelling that needs repr of a Str, which was deferred. repr was since decided on the ASCII domain, so the message is computable; this ADR builds the producing half, repr of a Str as a value, which 0028's printing had left unbuilt.
Both return together because differing behaviours for one class of condition is the thing to avoid. An out-of-range index and a missing key are the same kind of event, a lookup with no answer; shipping KeyError while a list index went on trapping would have created an inconsistency. So xs[i] raises now. The trap is gone from the program-visible surface.
0027's argument for checking an index in both modes is untouched. The runtime's bounds check remains in both modes, because a release build with no check would silently read capacity slots that no code had written. The change is who it blames: no program can reach the check any more, so it aborts naming a compiler defect. A raise is not a dropped check. An Array[T] subscript likewise still traps rather than raising, which keeps the numeric path out of the raiser analysis entirely.
The raise is in generated code by decision¶
The runtime's lookup answers an entry index or a miss and never raises, for three reasons; the third is the one that would have bitten:
- The raiser analysis can see a raise in generated code. A raise inside the runtime is invisible to it, so a caller would never check the pending slot and the exception would be swallowed at the first frame boundary, the one failure 0007's error-return lowering has no other guard for.
- The line number is the author's own.
- A helper that raised would have had to build
repr(key)itself, which puts a Str allocator and an exception dependency inside the container unit.
del d[k]¶
The base spec's disqualified-construct table has del as a statement (PP025). A157 amends the spec's §5.2: del of a subscript or a slice is a container operation, and del d[k] lowers as pop does (the question went upstream as A84).
Consequences¶
- A
dict's printed form and iteration order are held byte-for-byte to CPython; aset's are held to what Python specifies; the differential harness knows the difference. - A list comprehension over a
dictor asetworks with no new code: it desugars into the loop lowerings that already exist. Adictorsetcomprehension was refused when this ADR was written, since a dict comprehension has two element expressions whose evaluation order is observable; both lower since. __del__,isandid()stay refused.setis the first type whereiswould be actively wrong, since a set's membership is by value and CPython's is by identity-then-value.- The empty unannotated container literal (
xs = [],d = {},s = set()) was the shared blocker across all three container types, and was decided once for the three in 0031.
Alternatives considered¶
- A
setas adictwith no values: one runtime, one representation, and (being compact) insertion-ordered and byte-comparable. Rejected twice over: the compact layout costs an extra allocation for an ordering the type does not have, and, decisively, a set whose order happened to match CPython's would leave the order-insensitive comparison never exercised. - Refusing iteration and printing on a
setso every remaining comparison could stay byte-for-byte: rejected as a core operation removed from the language to keep a comparison passing, the wrong direction for the constrain-the-comparison rule. (The refusals A83 first placed on what shows a set's order were lifted by A179.)