What happens to a code object next: the frame, the value stack, the evaluation loop, inline caches right inside the bytecode, exceptions with no overhead, the check between instructions, and interpreter shutdown.
Commit to an output and a reason before you open the answer.
import dis
class P:
def __init__(self): self.x = 1
p = P()
def get(o): return o.x
dis.dis(get, adaptive=True)
for _ in range(200): get(p)
print("--- after 200 calls ---")
dis.dis(get, adaptive=True) 0 RESUME 0
2 LOAD_FAST 0 (o)
4 LOAD_ATTR 0 (x)
14 RETURN_VALUE
--- after 200 calls ---
0 RESUME_QUICK 0
2 LOAD_FAST 0 (o)
4 LOAD_ATTR_INSTANCE_VALUE 0 (x)
14 RETURN_VALUEThe instructions rewrote themselves based on actual execution. And note the offsets: there are ten bytes between 4 and 14, although there is only one instruction.def get(o): return o.x
print(get.__code__.co_code.hex(" "))97 00 7c 00 6a 00 00 00 00 00 00 00 00 00 53 0097 00 is RESUME, 7c 00 is LOAD_FAST, 6a 00 is LOAD_ATTR, then eight zero bytes, and 53 00 is RETURN_VALUE. The zeros are not alignment: they are four inline cache cells lying right in the instruction stream.import timeit
def with_try(n):
t = 0
for i in range(n):
try: t += i
except ValueError: pass
return t
def without(n):
t = 0
for i in range(n): t += i
return t
print(min(timeit.repeat(lambda: without(2_000_000), number=1, repeat=5)))
print(min(timeit.repeat(lambda: with_try(2_000_000), number=1, repeat=5)))
print(len(without.__code__.co_exceptiontable), len(with_try.__code__.co_exceptiontable))0.088
0.087
0 12Zero overhead. Entering a try executes not a single instruction — all information about the handler has been moved out into a separate twelve-byte table.def f(data):
err = None
try:
int(data)
except ValueError as err:
pass
return err
print(f("abc"))UnboundLocalError: cannot access local variable 'err'
where it is not associated with a valueThe variable is assigned twice — before the try and in the except — and is still unavailable. The compiler appended DELETE_FAST err to the end of the except block.Lesson 22 ended at the code object: an immutable structure with bytecode, constants, names and a precomputed stack depth. Here the second half begins — what the machine does with it.
CPython is a stack virtual machine. There are no registers: operands are pushed onto the value stack, an instruction pops them and pushes the result.
Execution is one loop for the whole process. _PyEval_EvalFrameDefault reads an instruction, executes it, moves on to the next. In 3.11 a call to a Python function does not enter it recursively — it pushes a new frame and continues the same loop.
Instructions rewrite themselves. Starting with 3.11 the machine replaces a generic instruction with a specialized one based on the types it actually observes, and keeps the observations right in the bytecode stream.
A frame is everything needed for one active call: the array of local variables, the value stack, a reference to the code object, the current instruction pointer f_lasti, and a reference to the calling frame.
In 3.11 the design changed fundamentally. Previously every call created a full frame object on the heap — with a reference count, a header and participation in garbage collection. Now frames are allocated one after another in a contiguous chunk of memory, one per thread (Include/internal/pycore_frame.h), and an actual object — a frame — is created only if someone asks for it: an exception traceback, sys._getframe(), a debugger, a profiler.
import sys, timeit
s = '''
import sys
def plain(n):
t = 0
for _ in range(n): t += 1
return t
def with_frame(n):
t = 0
for _ in range(n):
sys._getframe(); t += 1
return t
plain(100); with_frame(100)
'''
print(min(timeit.repeat("plain(1_000_000)", s, number=1, repeat=5)))
print(min(timeit.repeat("with_frame(1_000_000)", s, number=1, repeat=5)))
# → 0.033
# → 0.057 ← +23 ns for materializing the frame object
Twenty-three nanoseconds for every sys._getframe() is the price of exactly what ordinary execution no longer pays. Hence a practical point: a logging library that identifies the caller through the frame costs more than it seems, and in a hot loop this is visible.
Lesson 22, phase 6: the symbol table assigned indices to the local variables. So LOAD_FAST 0 reads element zero of an array rather than looking up a name. The array lies at the start of the frame, and right after it comes the value stack, exactly co_stacksize deep, a size known from compilation.
A consequence that regularly catches people in the debugger:
import sys
def f():
x = 1
sys._getframe().f_locals["x"] = 999
return x
print(f())
# → 1 ← the write had no effect
A function's f_locals is a snapshot assembled from the array on demand, not a live dictionary. You cannot write through it. At module level everything is different: there the locals are the globals, and f_locals is globals() is true.
An expression is broken down into postfix notation, as on a reverse Polish notation calculator:
import dis
def expr(a, b, c): return a + b * c
dis.dis(expr)
print(expr.__code__.co_stacksize)
# → 2 LOAD_FAST 0 (a)
# → 4 LOAD_FAST 1 (b)
# → 6 LOAD_FAST 2 (c)
# → 8 BINARY_OP 5 (*)
# → 12 BINARY_OP 0 (+)
# → 16 RETURN_VALUE
# → 3
Three values on the stack at the peak — exactly co_stacksize. There are no overflow checks during execution: the space is allocated in advance, because the compiler computed the maximum statically.
Python/ceval.c, the _PyEval_EvalFrameDefault function — several thousand lines, a branch per instruction. The format is simple: every instruction is exactly two bytes — an opcode and a one-byte argument. Arguments larger than 255 are assembled from EXTENDED_ARG prefixes.
Moving to the next instruction is not a switch but a computed goto: a table of label addresses (Python/opcode_targets.h), and at the end of each branch a direct jump to the address of the next opcode. This gives the processor a separate branch prediction point for each instruction instead of one shared one, and is worth about fifteen percent of speed.
import sysconfig
print(sysconfig.get_config_var("USE_COMPUTED_GOTOS"))
# → 1
A throughput measurement on this machine: a t += 1 loop of ten million iterations takes 0.325 s, that is, about six nanoseconds per bytecode instruction. For comparison, a call to an empty function is 27 ns, that is, roughly five instructions.
This is the main change of 3.11 (PEP 659) and a direct consequence of R2: types are unknown at compile time, so they have to be found out at execution time — and remembered.
Snippet B shows the mechanics in bytes. LOAD_ATTR has four cache cells, that is, eight bytes lying inside the instruction stream right after it. What is stored there is the type version and the attribute's offset. The CACHE opcode has number 0, and the evaluation loop simply steps over it.
import dis
print(dis.opmap["CACHE"], dis.opmap["LOAD_ATTR"])
# → 0 106
print(dis._inline_cache_entries[dis.opmap["LOAD_ATTR"]], "cells of 2 bytes")
# → 4 cells of 2 bytes
print(len(dis.opmap), "base opcodes,", len(dis._specialized_instructions), "specialized")
# → 110 base opcodes, 71 specialized
print(sum(1 for x in dis._inline_cache_entries if x), "opcodes carry a cache")
# → 11 opcodes carry a cache
How it works. At first there is a generic instruction with a “warm-up” counter. When the counter fires, the instruction turns into *_ADAPTIVE, which looks at the actual operands and rewrites itself into a narrowly specialized one: LOAD_ATTR_INSTANCE_VALUE, LOAD_ATTR_SLOT, LOAD_ATTR_MODULE, BINARY_OP_ADD_INT and so on. The specialized version checks only its own assumption — one comparison of the type version — and does the work directly.
If the assumption stops holding, the instruction deoptimizes back into the generic one. Hence the result from lesson 21: a homogeneous collection is traversed 1.4 times faster than a mix of classes. Not because the mix is “more complex”, but because the cache misses and the specialization does not hold.
This is not a JIT: no machine code is generated, the instructions remain bytecode. The JIT appeared in 3.13 and works on top of this mechanism, not instead of it.
Before 3.11 a call to a Python function meant a recursive entry into _PyEval_EvalFrameDefault: a C stack frame for every Python frame. Hence the historical pairing “recursion limit 1000, otherwise a segfault”.
In 3.11 the CALL instruction on a Python function simply pushes a new frame into the chunk and continues the same loop. The C stack does not grow:
import sys
sys.setrecursionlimit(30000)
def rec(n): return 0 if n == 0 else rec(n - 1)
print(rec(20000))
# → 0 ← twenty thousand frames, the process is alive
But sys.setrecursionlimit is still dangerous, and here is why: recursion that passes through C does consume the C stack. The __repr__ of a nested structure, an __eq__ with a recursive call, comparing deeply nested lists — all of this goes through C functions, and there the limit protects against real stack exhaustion, not against a logic error. You can raise the limit only if you know for certain that the recursion is pure Python.
Snippet C: a try in which nothing is raised costs exactly zero. Before 3.11, entering the block executed SETUP_FINALLY, which pushed a handler onto the block stack — that is, every pass was paid for, even when there were no exceptions.
Now the information about handlers has been moved out into co_exceptiontable — a table that is not executed but read only at the moment of a raise:
import dis
def with_try(n):
t = 0
for i in range(n):
try: t += i
except ValueError: pass
return t
for e in dis._parse_exception_table(with_try.__code__):
print(e)
# → _ExceptionTableEntry(start=40, end=50, target=52, depth=1, lasti=False)
# → _ExceptionTableEntry(start=52, end=72, target=78, depth=2, lasti=True)
# → _ExceptionTableEntry(start=76, end=78, target=78, depth=2, lasti=True)
It reads like this: “if an exception occurred at an offset from 40 to 50, jump to 52, unwinding the stack to depth 1”. On a raise the interpreter takes the current f_lasti, looks for a matching row, and if there is none, pops the frame and searches in the caller. That is stack unwinding.
| 300,000 operations | time |
|---|---|
try, the key is present | 0.0147 s |
if key in d, the key is missing | 0.0149 s |
try, the key is missing — the exception flies | 0.0559 s |
While it does not raise, it is free; when it raises, it is 154 nanoseconds apiece. That is the precise formulation of when EAFP beats LBYL and when it loses.
The evaluation loop has one flag that is checked at instruction boundaries — the eval breaker. It combines everything that has to happen “not right now, but soon”: a request to give up the GIL (lesson 19), an OS signal that has been delivered, pending calls.
Hence three things that are usually known separately:
x += 1 is still a race: it is several instructions.Lesson 13 said: a generator keeps a suspended frame. Here you can see that this is literal:
def gen():
a = 1
yield a
b = 2
yield a + b
g = gen()
print(g.gi_frame.f_lasti) # → 0 not started yet
next(g)
print(g.gi_frame.f_lasti, g.gi_frame.f_locals) # → 12 {'a': 1}
next(g)
print(g.gi_frame.f_locals) # → {'a': 1, 'b': 2}
try: next(g)
except StopIteration: pass
print(g.gi_frame) # → None the frame is released
yield does not destroy the frame; it saves f_lasti and hands over control. The next next continues from the same instruction. A generator's frame cannot live in the thread's shared chunk — it outlives the call — so for a generator the frame is copied into the generator object.
await rests on the same mechanism: a coroutine is the same suspended frame, only with a different resumption protocol (lesson 14).
Py_FinalizeEx in Python/pylifecycle.c takes the interpreter apart in a fixed order. The order is observable:
import atexit
class Noisy:
def __init__(self, name): self.name = name
def __del__(self): print("__del__", self.name)
keep = Noisy("module variable")
atexit.register(lambda: print("atexit ran"))
def main():
local = Noisy("local")
print("main finished")
main()
print("end of module")
# → main finished
# → __del__ local ← reference count, right on exit from the function
# → end of module
# → atexit ran ← before the modules are taken apart
# → __del__ module variable
The local dies by reference count at the moment the function exits (lesson 09). atexit runs while the modules are still intact. Module globals are cleared last — and this is where the zone begins in which __del__ is no longer guaranteed: modules are partly taken apart, there are no more imports, the order is undefined 🕳.
And os._exit bypasses all of this entirely: it ends the process with a system call, letting neither atexit nor destructors nor buffer flushing run. Sometimes this is exactly what is needed after a fork; in all other cases it is a way to lose data.
Everything in this chapter is a 🔧 implementation detail. The set of opcodes, their numbers, the presence of inline caches, the exception table format, the structure of a frame — none of this is part of the language or guaranteed between versions. 3.10 bytecode is literally incompatible with 3.11: different opcodes.
The boundaries have already moved. In 3.12 the evaluation loop is generated from Python/bytecodes.c, new instructions were added and old ones removed. 3.13 brought a copy-and-patch JIT: some hot regions are now turned into machine code after all. In 3.13+ there is a build without the GIL, and the eval breaker works differently there.
Specialization is not observable from the language. dis.dis(f, adaptive=True) shows the current state of the instructions, but there is no “did the specialization work” API, and none is planned. The only reliable way to find out whether data homogeneity helped is to measure.
The recursion limit is a counter, not a measurement of the stack. For pure-Python recursion in 3.11 it protects against an infinite loop; for recursion through C it protects against real exhaustion of the C stack, and there the margin has to be real. One number serves two different purposes, and that is a compromise, not a solution.
The chapter shows R2 · attributes are resolved at runtime from the side where it is paid for. For twenty years obj.x meant a full lookup on every access; PEP 659 did not abolish the dynamism but placed a bet: in real code the type at an access site is almost always the same. The inline cache remembers that bet and checks it with one comparison.
From here the reverse is visible too: where the bet does not pay off — a mixed collection, a class that changes on the fly — the specialization deoptimizes and the cost comes back. Dynamism is not free; it is just deferred until the moment it is actually used.
The second root here is R3. The eval breaker exists because the reference count is non-atomic and the GIL is needed, and the GIL has to be handed to someone. Checking the flag between instructions is the price of a decision about the memory model, placed in the hottest loop of the interpreter.
And the third thing that is visible only here: the boundary of atomicity in Python is the boundary of a bytecode instruction, not of a line of code. Everything lesson 19 says about races follows from this one fact.
The call stack in C and frames in Python are the same thing, but at a different price.
In C a call is the processor's call instruction: the return address goes onto the hardware stack, local variables are addressed as offsets from the frame pointer. The hardware does all of this, at a cost of a few nanoseconds.
In Python a call takes 27 nanoseconds, because the interpreter does the same thing by hand: it allocates space for the frame, copies the arguments into the locals array, sets the instruction pointer. The idea is identical — a local variable is an index, not a name — and the difference is exactly that in C the frame is laid out by the compiler, while here it is assembled by a program.
The 3.11 change made the resemblance even closer: previously each frame was a separate object on the heap, now they lie one after another in a single chunk of memory, like frames on a real stack. One difference remains, but a fundamental one: between instructions Python checks a flag. The processor checks nothing between instructions — it has no GIL to give up and no signals to deliver to a Python handler.
Questions that come up on their own if you read closely. The answer is under the question.
Because it was too late to change, and the gain is not big enough to justify the breakage.
A register machine addresses operands directly: ADD r3, r1, r2 instead of three loads onto the stack and an addition. There are fewer instructions, each one is fatter, and there are fewer dispatches too. LuaJIT builds one of the fastest dynamic runtimes on this.
What gets in Python's way. Bytecode is not the interpreter's private business: dis, debuggers, profilers, coverage, py-spy, tracing tools, decompilers and some libraries all look at it. Changing the model would break that whole layer at once, and the gain — tens of percent, by various estimates — does not pay for that. This is R9 in pure form.
On top of that the stack model has real merits: the compiler is simpler (no register allocation), the bytecode is more compact in bytes per instruction, and generating code from the AST is almost mechanical.
And most importantly, 3.11 took a different road to the same goal. Instead of changing the model, it added specialization: the instruction stays stack-based but rewrites itself for specific types, and part of the work moves into the inline cache. The gain is comparable, and nothing had to be broken. The JIT in 3.13 continues the same line — it works on top of bytecode, not instead of it.
The difference is simple: a JIT produces machine code, specialization does not.
Specialization in 3.11 changes which bytecode instruction will be executed: a generic LOAD_ATTR is replaced by LOAD_ATTR_INSTANCE_VALUE. It is still executed by the evaluation loop, reading two bytes at a time. No code generation happens — a narrower branch in ceval.c is simply chosen, and it does fewer checks.
A JIT takes a sequence of instructions and generates native code for it, which the processor executes directly. Dispatch disappears entirely rather than shrinking.
| specialization (3.11) | JIT (3.13+) | |
|---|---|---|
| what comes out | a different opcode | machine code |
| who executes it | the evaluation loop | the processor |
| warm-up cost | a counter and one rewrite | compiling a region |
| works on its own | — | no, it needs specialization |
And they are not alternatives but floors of one building. The copy-and-patch JIT in 3.13 takes already specialized instructions and stitches together precompiled machine-code templates for them. Without specialization it would have to generate generic code with type checks — that is, the same interpreter, only unrolled.
That is why PEP 659 was not a “stopgap until the JIT” but the foundation for it.
A historical value, chosen so as never to overflow the C stack. Today it protects two different things with one number.
Before 3.11 every call to a Python function meant a recursive entry into _PyEval_EvalFrameDefault, that is, a frame on the C stack. A thread's stack is 8 MB by default, an interpreter frame is a few hundred bytes, hence the order of a thousand with a margin for deep frames and nested C calls.
In 3.11 the picture changed: a call to a Python function no longer consumes the C stack, and pure recursion runs only into the counter:
import sys
sys.setrecursionlimit(30000)
def rec(n): return 0 if n == 0 else rec(n - 1)
print(rec(20000)) # → 0 twenty thousand frames, the process is alive
But raising the limit is still dangerous, and here is why: recursion that passes through C consumes the real stack. The __repr__ of a nested structure, an __eq__ with a recursive call, comparing deeply nested lists, serialization — all of this goes into C functions. There the limit protects against a real overflow, and exceeding it gives not a RecursionError but a segfault: the process dies silently, without a traceback.
In practice. You can raise the limit only if you know for certain that the recursion is pure Python. More reliable is to rewrite it as a loop with an explicit stack: for traversing trees and graphs this is almost always possible, and it settles the question of depth as well. And it is worth turning on faulthandler.enable() — then a segfault will at least leave a Python traceback.
frame object is materialized only on demand, at a cost of 23 ns. An expression is broken down into postfix notation on the stack. The evaluation loop reads two bytes per instruction and jumps with a computed goto — about six nanoseconds per instruction, 27 per function call. The main change of 3.11: instructions rewrite themselves — 110 base opcodes, 71 specialized ones, and the observations are kept in inline caches right inside the bytecode stream; the eight zero bytes after LOAD_ATTR are those caches. A call to a Python function no longer consumes the C stack, so twenty thousand frames of recursion do not bring the process down — but recursion through C still does consume it. A try without a raise costs exactly zero: the handlers have been moved out into a table that is read only on an exception; the raise itself costs 154 ns. Between instructions the eval breaker is checked — hence the GIL switching, the fact that Ctrl-C does not interrupt a call in C, and the fact that the boundary of atomicity runs along an instruction, not along a line. A generator is the same frame, but with a saved f_lasti. At shutdown, locals die by reference count, then atexit runs, and module globals go last, already in the zone where __del__ is not guaranteed. Everything listed here is 🔧 through and through: in 3.12 the loop is generated from a different file, and in 3.13 a JIT appeared on top.The JVM. Also a stack machine with bytecode, but with a JIT from the very start: HotSpot profiles, compiles hot methods into machine code and inlines aggressively. The reason this turned out to be easier: in Java the type is known statically, and the compiler can reason about it. In Python the inline cache has to check its assumption on every access — that is no longer an optimization but insurance.
V8 in JavaScript. The closest relative by task: dynamic types, objects as dictionaries. The solution is similar and appeared much earlier — hidden classes and inline caches. PEP 659 largely carries this idea over into CPython, with the difference that V8 generates machine code, while CPython stayed a pure interpreter until 3.13.
Lua. Also a bytecode interpreter, but a register machine instead of a stack machine: instructions address operands directly rather than through the stack. There are fewer instructions, each one fatter. LuaJIT builds one of the fastest dynamic runtimes of all on this. CPython stayed stack-based for compatibility reasons — the switch would have broken every tool that works with bytecode. This is R9 in pure form.
Why CPython had no JIT for so long. Not for lack of will: attempts went on for twenty years (Psyco, Unladen Swallow, Pyston, Pyjion). What got in the way was the same thing that gets in the way of removing the GIL — the C API from lesson 15. An extension can get a pointer to any object and do anything with it, so a JIT can treat almost nothing as proven.
except is deleted after the blockThe variable is assigned twice and is still unavailableParsing an external service's response. We want to keep the error rather than lose it, and return it upwards together with the result.
def parse_amount(raw):
err = None
value = None
try:
value = int(raw)
except ValueError as err: # ← right here
pass
return value, err
What happens. On the success path everything works: err stays None. On the error path — UnboundLocalError on the return line, because the compiler appends a DELETE_FAST err instruction to the end of the except block.
Why it was done. An exception object holds a reference to the traceback, the traceback to the frames, the frames to all local variables. Leaving the name bound would create a cycle frame → exception → traceback → frame and extend the life of the whole frame's contents until the collector's next pass (lesson 10). Python 3 solved this radically: the name is deleted on leaving the block, always, unconditionally — even if it existed before the try.
Why it passes review. Initializing err = None right above the try looks like exhaustive protection. The test for the success path is green. The test for the error often checks only that “None came back in value” and does not look at the second element.
Check it:
import dis
print(any(i.opname == "DELETE_FAST" and i.argval == "err"
for i in dis.get_instructions(parse_amount)))
# → True
How to fix it. Move it into another name inside the block — the only way that works:
def parse_amount(raw):
err = None
value = None
try:
value = int(raw)
except ValueError as exc:
err = exc # exc will die, err will remain
return value, err
The general rule. The name after as lives exactly until the end of the except block and does not survive it under any circumstances. If the exception object is needed later, assign it to another name inside the block.
try without a raise is free; with a raise it costs 154 nsThe “ask forgiveness or permission” argument is usually conducted on style. It is settled by measurement, and the answer favours neither side.
import timeit
def eafp(d, keys):
t = 0
for k in keys:
try: t += d[k]
except KeyError: t += 1
return t
def lbyl(d, keys):
t = 0
for k in keys:
if k in d: t += d[k]
else: t += 1
return t
| 300,000 accesses | EAFP (try) | LBYL (if in) |
|---|---|---|
| the key is always there | 0.0147 s | 0.0149 s |
| the key is never there | 0.0559 s | 0.0149 s |
When there are no misses, the forms are indistinguishable, and try is even slightly faster, because LBYL does an extra membership check. When misses are constant, try loses by a factor of 3.8, and the whole difference goes into creating the exception object, building the traceback and unwinding.
The rule that follows from the mechanism: try is cheaper as long as the exception really is an exception. The threshold is roughly ten percent misses: rarer — EAFP wins and reads better; more often — this is not error handling but control flow through exceptions, and it has to be rewritten.
Where this is caught in practice. Parsing input data where half the records are invalid. Walking a tree with try: node.child except AttributeError at the leaves. A cache with a low hit rate. In all three cases the exception is the norm, not the exception, and the cost accumulates.
What this measurement does not say. That try should be avoided. On the contrary: since it is free in the absence of a raise, wrapping it around blocks where an error is rare is right and costs nothing. All that changed is that before 3.11 this was not true, and old benchmarks showed overhead even on the success path.
The first — see how instructions rewrite themselves, on your own code:
import dis
class P:
__slots__ = ("x",)
def __init__(self): self.x = 1
class Q:
def __init__(self): self.x = 1
def get(o): return o.x
p, q = P(), Q()
for _ in range(200): get(p)
dis.dis(get, adaptive=True) # which specialization was chosen for __slots__?
for _ in range(200): get(q) # and now another type is mixed in
dis.dis(get, adaptive=True) # what happened to the instruction?
A question: is the specialization for __slots__ and for an ordinary class the same instruction or different ones? What happens when both types arrive at the same access site?
The second — caches in bytes:
import dis
def f(o): return o.x
code = f.__code__.co_code
print(code.hex(" "))
print("length", len(code), "bytes")
for name in ("LOAD_ATTR", "CALL", "BINARY_OP", "LOAD_GLOBAL", "FOR_ITER"):
print(name, dis._inline_cache_entries[dis.opmap[name]], "cells")
The third — the exception table, and its absence:
import dis
def clean(n):
t = 0
for i in range(n): t += i
return t
def guarded(n):
t = 0
for i in range(n):
try: t += i
except ValueError: pass
return t
print(len(clean.__code__.co_exceptiontable), len(guarded.__code__.co_exceptiontable))
for e in dis._parse_exception_table(guarded.__code__): print(e)
The fourth — where the recursion boundary lies:
import sys
sys.setrecursionlimit(30000)
def pyrec(n): return 0 if n == 0 else pyrec(n - 1)
print(pyrec(20000)) # pure Python — goes through
# And now recursion that goes through C.
# Careful: at a large depth this will crash the process for real.
x = []; cur = x
for _ in range(200):
nxt = []; cur.append(nxt); cur = nxt
print(len(repr(x))) # repr is recursive and goes through C
sys.setrecursionlimit(1000)
A question about the last one: why does one and the same limit protect two fundamentally different things, and what exactly will happen if you raise it to a million?
Lib/dis.py. Besides dis.dis: _parse_exception_table shows the table from phase 7 of lesson 22, _inline_cache_entries shows how many cache cells each opcode has, _specialized_instructions is the full list of specializations. All with an underscore, that is, with no promises, but it is the only way to see the mechanism.
sys.settrace and sys.setprofile. The hooks that pdb, coverage and profilers stand on. An important consequence of this chapter: tracing that is switched on forces a frame object to be materialized on every call and disables some optimizations — hence the tenfold slowdown under coverage, and hence the rule not to measure performance under a debugger.
faulthandler. Prints a Python traceback on a segfault and on a timeout. Exactly the tool you need when a process dies silently from C stack exhaustion or a crash in an extension. One line of faulthandler.enable() at the entry point pays for itself at the very first incident.
Lib/traceback.py. It reads in twenty minutes and clears up the questions about __cause__, __context__ and raise ... from. Useful together with lesson 12.
py-spy (github.com/benfred/py-spy). Reads another process's frames straight from memory, without its participation. It works precisely because the frame layout is a fixed structure: py-spy knows it for every CPython version and walks the f_back chain from the outside.
An instruction in bytes. Always two bytes: an opcode and an argument. Arguments larger than 255 are built up with EXTENDED_ARG prefixes, each adding eight high bits — up to three prefixes, that is, up to a 32-bit argument.
import dis
code = compile("x = " + " + ".join(str(i) for i in range(300)), "<s>", "exec")
print(any(i.opname == "EXTENDED_ARG" for i in dis.get_instructions(code)))
# → False ← the sum of three hundred literals was folded into one constant back in phase 5
big = compile("d = {" + ",".join(f"'k{i}': {i}" for i in range(400)) + "}", "<s>", "exec")
print(sum(1 for i in dis.get_instructions(big) if i.opname == "EXTENDED_ARG"))
# → 537 ← four hundred keys are not folded, the indices went past 255
The first result is a reminder that phase 5 runs earlier: folding arithmetic is cheaper than generating instructions for it. The second shows why the prefix is needed at all.
Inline caches by opcode. Eleven instructions carry a cache; the size is chosen for what needs to be stored:
| instruction | cells (2 bytes each) | what is stored |
|---|---|---|
LOAD_ATTR | 4 | The type version and the attribute's offset |
LOAD_METHOD | 10 | The type version, the method itself, binding flags |
CALL | 4 | The shape of the callee: function, method, C function |
BINARY_OP | 1 | A warm-up counter; after that the opcode is replaced entirely |
LOAD_GLOBAL | 5 | The versions of the module's and builtins' dictionaries, plus an index |
This is why dict got a version counter: a specialized LOAD_GLOBAL checks that the global dictionary has not changed with one integer comparison instead of a hash lookup. A direct link to lesson 05.
The cost of operations, measured.
| operation | nanoseconds |
|---|---|
| one bytecode instruction | ≈ 6 |
| calling a Python function | 27 |
| calling a method (on top of a function call) | +5 |
materializing a frame object (sys._getframe) | 23 |
| raising and catching an exception | 154 |
entering a try, if nothing is raised | 0 |
Hence an estimate that is useful when reading a profile: a function of ten lines of simple code is on the order of a hundred instructions, that is, roughly 600 nanoseconds plus 27 for the call itself. If it costs ten microseconds in the profile, the time goes not into interpretation but into something inside it.
The frame layout. In memory, one after another: a header (_PyInterpreterFrame: a reference to the code object, to the previous frame, to globals and builtins, the instruction pointer), then the locals array of co_nlocals elements, then the value stack of co_stacksize elements. Nothing dynamic — the size is known from the code object, so allocating a frame is a pointer bump in the thread's chunk.
Why this gave 3.11 its speed-up. The old frame object was an ordinary Python object: a header with a reference count, participation in garbage collection, a separate allocation and deallocation on every call. The new scheme removed all of this from the hot path and kept it only where the object was actually requested.
| what | file |
|---|---|
| the evaluation loop | Python/ceval.c — look for _PyEval_EvalFrameDefault |
| the jump table | Python/opcode_targets.h — generated, but worth a look |
| opcode numbers | Include/opcode.h |
| specialization | Python/specialize.c — this is where the decision is made about what to turn an instruction into |
| the cache format | Include/internal/pycore_code.h |
| the frame | Include/internal/pycore_frame.h — the whole layout in one structure |
| the frame object | Objects/frameobject.c — materialization and f_locals |
| calls | Objects/call.c — the call protocols, including vectorcall |
| exceptions | Python/errors.c; unwinding is in ceval.c |
| the eval breaker and the GIL | Python/ceval_gil.h |
| generators | Objects/genobject.c — how the frame moves into the object |
| shutdown | Python/pylifecycle.c — Py_FinalizeEx |
Where to start if you open one file. Python/specialize.c: the comment at the top sets out the whole idea of PEP 659 in words, and then there is one function per family of instructions — you can see exactly what assumptions the machine makes about your code.
One trick for reading ceval.c. Do not read it front to back. Take an instruction from dis.dis of your own code, find TARGET(LOAD_ATTR) in the file and read that one block. Each branch is self-contained and fits on a screen.
What changed after 3.11. In 3.12 ceval.c no longer contains the instruction bodies — they moved to Python/bytecodes.c, from which both the loop and the tables are generated. The structure reads differently; the ideas are the same.
obj.x, end to end — the attribute lookup procedure; here you can see how its result is cached right in the instruction, and what happens when the cache misses.yield from and L14 · async/await — the suspended frame from section 9 is their common foundation.try became free, and why the name after as is deleted.ceval.c, and the rest of the series covers frames, objects and the GIL.