The Canon / registry

Guarantee or detail

What in Python you can lean on architecturally, what to use with a caveat, and what not to pin down even with a test.

One question separates knowing the language from knowing the implementation: will my code break on another implementation or in the next release? Below is a registry of every non-obvious point in the canon, sorted by that question. There is no need to read it in order: the page is meant as a reference to come back to.

🔒Language guarantee. Fixed by the specification or the documentation. Lean on it with confidence — if it breaks, that is a bug in the interpreter.
🔧CPython detail. It works and will most likely keep working. But nobody promised: on PyPy or in the next minor release it may disappear without warning.
🕳Undefined. Depends on the platform, the build, the order of execution, or simply has not been fixed by anyone. Do not lean on it even in tests.

In the registry: 25 guarantees · 25 details · 7 undefined

How to use this in practice. The rule is simple: 🔒 can be built into the architecture; 🔧 can be used but must not be made load-bearing; 🕳 must not be checked with a test — the test will stay green exactly until it runs on someone else's machine. And separately: if a 🔧 is needed as load-bearing, that has to be written down in the code as a comment, and in the requirements as “CPython version such-and-such only”.

The object model and names

🔒
is compares identity, == compares value; identity is unique for the object's lifetime
You can lean on it. But an address is reused after the object dies, so id() must not be stored as a long-lived key — it will collide with someone else's.
chapter 01 →
🔧
id() returns the object's address in memory
True for CPython. The language promises only that the number is unique among living objects; on PyPy it is not an address.
chapter 01 →
🔒
An argument default is evaluated once, when def executes
This is fixed semantics, not an oversight. A mutable default is dangerous precisely because the behaviour is guaranteed.
chapter 01 →
🔧
Small integers from −5 to 256 are cached: a is b is true for them
The bounds of the range have changed and are not documented as a contract. Never compare numbers with is.
chapter 02 →
🔧
Identical literals within one code object are one object
Constant folding by the compiler. Inside a function 'ab' is 'ab' is true, while the same string assembled at runtime is already a different object.
chapter 01 →
🔧
Which strings are interned automatically
Depends on whether it is a literal and whether it looks like an identifier; it has changed between versions. Only an explicit sys.intern carries a guarantee.
chapter 02 →

Numbers

🔒
int has arbitrary precision; // rounds down, and the sign of % matches the sign of the divisor
This is the language specification, not a property of the implementation. This is exactly where Python parts ways with C, where division truncates towards zero.
chapter 02 →
🔧
The internal representation of int: an array of 30-bit digits, sys.getsizeof(2**70) == 36
The specific sizes and the digit width are a build detail. 3.12 also added a limit on the length of the decimal representation.
chapter 02 →
🔒
float is an IEEE 754 double with all its properties
You can lean on it: 0.1 + 0.2 != 0.3 here for exactly the same reason as in C.
chapter 02 →

Containers, dict, hashes

🔒
Amortized complexity: list.append is O(1), list.insert(0, …) is O(n), x in list is O(n), x in set and x in dict are O(1)
Written in the documentation and part of the contract. Anything derived from complexity is safe.
chapter 03 →
🔧
The list growth pattern (0, 4, 8, 16, 25, 35, …) and the moment the buffer shrinks
The formula has changed and may change again. Relying on a specific sys.getsizeof of a list is a way to write a fragile test.
chapter 03 →
🔒
dict preserves insertion order (since 3.7)
A rare case: in 3.6 it was an implementation detail 🔧, in 3.7 it became a guarantee — because code already relied on it. The canonical example of how a detail becomes a promise.
chapter 05 →
🕳
The iteration order of a set
Looks stable within a run, depends on the hashes and the insertion history. Never rely on it, not even in tests.
chapter 05 →
🕳
The specific value of hash('string') across process runs
Randomized with a salt (PYTHONHASHSEED) — protection against collision attacks. Hence: a hash must not be saved to disk.
chapter 05 →
🔒
The hash contract: a == b implies hash(a) == hash(b), and the hash does not change during the object's lifetime
Breaking the contract is not an interpreter error but silent loss of keys. Hence the ban on mutable keys.
chapter 05 →
🔧
The compact dict layout, shared instance keys (PEP 412), values stored in the object's preamble
What is guaranteed is behaviour and complexity, not bytes. The layout changed in 3.3, 3.6 and 3.11.
chapter 05 →
🕳
Mutating a list while iterating over it
Not forbidden and not checked — it simply skips elements. For dict and set the same operation gives an explicit RuntimeError 🔒.
chapter 03 →

Attributes, classes, protocols

🔒
The lookup order: data descriptor on the type → the instance's __dict__ → the type's MRO → __getattr__
The procedure is fixed by the language. All the behaviour of property, classmethod and super() follows from it.
chapter 04 →
🔒
The MRO is computed by C3 linearization; super() follows the MRO of the instance, not the class's parent
You can lean on it. It follows that cooperative multiple inheritance works only if every participant in the chain plays along.
chapter 06 →
🔒
Special methods are looked up on the type, bypassing __getattr__ and the instance's __dict__
Hence: a dunder assigned to an instance does not work; proxy objects are forced to list their dunders explicitly.
chapter 11 →
🔧
The type's slots are updated when a dunder is assigned to a class after it was created
It works, but it is the mechanics of type.__setattr__ in CPython, not a promise.
chapter 11 →
🔧
__slots__ saves memory; the specific saving in bytes
The effect is guaranteed qualitatively (there is no __dict__), the size is not: it depends on the version, because the instance layout has changed.
chapter 04 →
🔧
Inline caches and bytecode specialization (PEP 659) speed up attribute access and calls
The speed-up is real and measurable, but the conditions under which it kicks in are not documented. A monomorphic loop is faster than a polymorphic one — 1.4 times on 3.11, differently on another version.
chapter 21 →

Lifetime, memory, resources

🔒
An object will be destroyed, and when destroyed it will release its resources
The fact is guaranteed, not the moment. This is exactly the line around which the whole of root R3 is built.
chapter 09 →
🔧
Destruction happens immediately when the reference count drops to zero
The most expensive detail in the whole canon: half of all Python code ever written relies on it (open(…).read() without with). PyPy, GraalPy and Jython behave differently, and that is not their bug.
chapter 09 →
🕳
The order of finalization at interpreter exit; whether __del__ is called at all
By the time of exit the modules are partly taken apart. No critical work should hang on __del__ — only on with or atexit.
chapter 10 →
🔧
The generation thresholds (700, 10, 10) and the three-generation scheme itself
The scheme was reworked in 3.12. The idea “young objects are checked more often” remained, the numbers did not.
chapter 10 →
🔧
Returning memory to the OS through pymalloc arenas; RSS as an indicator
Freeing an object and returning memory to the OS are different events. Hence: a growing RSS does not prove a leak, and a stable one does not prove its absence.
chapter 10 →
🔒
with calls __exit__ on any exit from the block, including an exception and return
Lean on it with confidence. It is the only mechanism of deterministic release that the language actually promises.
chapter 12 →
🔒
An __exit__ that returns a true value suppresses the exception
A power a C++ destructor does not have. Hence contextlib.suppress.
chapter 12 →
🔒
return or break in finally swallows an exception in flight
Fixed semantics, not a bug. 3.14 added a compiler warning for it but left the behaviour alone.
chapter 12 →

Iteration, generators, async

🔒
An iterator is single-use, and iter(it) is it for any iterator
Hence: a function that accepts a “sequence” silently breaks on a generator passed to it if it goes over it twice.
chapter 13 →
🔒
yield from passes send, throw and the return value straight through
An ordinary loop for x in gen: yield x does not do this. await stands on this difference.
chapter 13 →
🔧
The moment an abandoned generator receives GeneratorExit and runs its finally
That it will receive it is guaranteed; the moment is not: it inherits the uncertainty of the moment of destruction. The same logic as with a file without with.
chapter 13 →
🔒
Between two awaits a coroutine's code runs without preemption
Hence the main property of asyncio: there are no races within one step, but one synchronous call blocks the whole process.
chapter 14 →

Parallelism

🔒
The GIL does not make compound operations atomic
x += 1, “check and write”, “read and update” are races despite the GIL. The right answer is always a lock or a queue.
chapter 19 →
🔧
The list of “atomic operations” that wanders around the internet
It describes the bytecode compiler of a specific version. Code must not rely on it — specialization in 3.11+ has already moved the instruction boundaries.
chapter 19 →
🔧
The thread switch interval is 5 ms, configurable with sys.setswitchinterval
The default value and the switching model itself are details. Reducing the interval does not make code correct; it only changes the probability of seeing the race.
chapter 19 →
🔧
numpy releases the GIL in heavy operations — hence 1.9× on two threads
Not every function releases it, and small operations do not release it at all: the overhead exceeds the gain. This is checked by measurement, not by faith.
chapter 15 →
🕳
fork from a process that has threads
The child is left with locks taken by threads that do not exist. Hence hangs, and the move to spawn by default.
chapter 20 →
🔧
Free-threading (PEP 703) as a separate interpreter build
Not a behaviour switch but a separate ABI and separate wheels — a direct consequence of R9. Extensions have to be rebuilt and checked for thread safety.
chapter 19 →

Import, types, packaging

🔒
A module's body executes exactly once per process, and the result is cached in sys.modules
Hence: everything at the top level is process-wide global state that leaks between tests.
chapter 17 →
🔒
The module object goes into sys.modules before its body executes
That is exactly why a circular import gives a “partially initialized module” rather than infinite recursion.
chapter 17 →
🔒
from x import y creates a separate binding in the importing module
Hence the one rule of patching: patch where it is used, not where it is defined.
chapter 17 →
🔒
Annotations are not checked at runtime; x: int in a class body does not create an attribute
An annotation is data in a dictionary. All the behaviour of dataclass and pydantic follows from someone reading that data.
chapter 18 →
🔧
When exactly annotations are evaluated and what lies in __annotations__
PEP 563 never became the default, and PEP 649 changes the model again. Code that reads types at runtime is sensitive to the version.
chapter 18 →
🕳
ABI compatibility of a compiled extension between minor versions
Breaks every release unless built for abi3. Hence the wheel matrix and “the package will not install on the new Python”.
chapter 16 →

The compilation pipeline and the execution machine

🔒
A module's body is compiled and executed, and the result is cached — but what is cached is not described by the language
The fact of caching and its transparency are guaranteed. The .pyc format, the magic number and the contents are not: a .pyc from another minor version is simply ignored.
chapter 22 →
🔒
A name that is assigned anywhere in a function is local throughout the function
The decision is made by the symbol table at compile time, statically, without control-flow analysis. Hence UnboundLocalError, global and nonlocal. This is the specification, not a detail.
chapter 22 →
🔒
The name after except ... as is deleted on leaving the block
Always and unconditionally, even if it existed before the try. Done so that the traceback does not keep the frame alive. If you need the object later, assign it to another name inside the block.
chapter 23 →
🔧
Validation of .pyc by the source's modification time and size
A default, not a requirement: PEP 552 provides validation by hash. Deploy code so that the mtime ends up older than the recorded one, and the old bytecode will run.
chapter 22 →
🔧
The set of opcodes, their numbers, the presence of inline caches, the exception table format
Changes every release. 110 base opcodes and 71 specialized ones are the numbers for 3.11; in 3.12 the evaluation loop is generated from a different file and the set is different.
chapter 23 →
🔧
A try without a raise costs nothing
True since 3.11 and only for CPython: the handlers have been moved out into co_exceptiontable, which is read only on an exception. Before 3.11 entering the block executed an instruction, and benchmarks from those years show overhead.
chapter 23 →
🔧
A call to a Python function does not consume the C stack
Appeared in 3.11: CALL pushes a frame and continues the same loop. That is why 20,000 frames of recursion do not bring the process down — but recursion through C still consumes the stack, and there the limit offers real protection.
chapter 23 →
🕳
The moment the __del__ of a module-level global is called at exit
By that point the modules are partly taken apart, the order is undefined, and the call may not happen at all. atexit runs earlier and more reliably; os._exit lets nothing run.
chapter 23 →

Performance

🔧
Any specific number in this canon
Everything was measured on CPython 3.11, Linux, x86-64. The order of magnitude is stable, the specific figure is not. Measure on your own version and your own data.
chapter 21 →
🔧
“A list comprehension is faster than a loop with append”
On 3.11 the difference is 6% — the advice became obsolete together with the version it was written for. An example of how an implementation detail gets fixed in folklore.
chapter 21 →
Where this table comes from. Not from the documentation: it is not collected in one place there, and half of the 🔧 rows are missing from the documentation precisely because documenting an implementation detail means turning it into a promise. Every row is derived from the mechanism in the corresponding chapter; if a claim seems debatable, take the argument up with the chapter, not with the table.

Written by · The Python Canon