How CPython runs code
One function's path through CPython 3.14: tokens, the syntax tree, bytecode and `dis`, the evaluation loop with its value stack and frames, the specializing adaptive interpreter, reference counting, the cycle collector, immortal objects and the experimental JIT.
Not line by line
The topic Debugging and profiling taught you to measure. timeit times a statement, cProfile shows which function eats the time, and pdb walks the frames of a running program. Two questions stayed open. Why does one operation cost nanoseconds and another many times more? And what exactly are the frames that the debugger walks? This topic opens the Under the hood module and answers both from inside the interpreter.
A common picture of an interpreter is a program that reads a line of text, works out what it means, does it, and reads the next line. If CPython worked like that, a loop that runs a million times would parse its body a million times. A syntax error on the last line would show up only after the first lines had run. And nothing could make the same line faster on its second run.
None of that holds. The topic Running Python gave the outline: CPython first compiles the whole file into bytecode, and then a loop written in C executes the bytecode. So a syntax error anywhere stops the file before its first line runs, and a loop body is analysed once. The same line even gets faster after a few runs, as a later block shows.
This topic follows one small function through every stage:
def f(price, qty):
total = price * qty
return total + 1The stages are tokens, a syntax tree, bytecode, the evaluation loop with its value stack and frames, and the rewriting of instructions as the interpreter learns the types it sees. Then comes memory: reference counts, the cycle collector and immortal objects.
All output here comes from CPython 3.14.7. Instruction names, specializations and collector thresholds are CPython details. Bytecode differs between versions: even 3.13 prints a different listing for f. Other implementations, such as PyPy, have none of this.
Tokens and the syntax tree
Take one statement, total = price * 2. The first stage, the tokenizer, cuts the text into tokens: names, operators, numbers and markers for the end of a line. The module tokenize exposes it:
import io, tokenize
src = "total = price * 2\n"
for tok in tokenize.generate_tokens(io.StringIO(src).readline):
print(tokenize.tok_name[tok.type], repr(tok.string))NAME 'total'
OP '='
NAME 'price'
OP '*'
NUMBER '2'
NEWLINE '\n'
ENDMARKER ''The parser checks that the tokens follow the grammar and builds an abstract syntax tree (AST). It has one node per construct; the punctuation is gone and the structure is explicit. The module ast prints it:
import ast
print(ast.dump(ast.parse("total = price * 2"), indent=2))Module(
body=[
Assign(
targets=[
Name(id='total', ctx=Store())],
value=BinOp(
left=Name(id='price', ctx=Load()),
op=Mult(),
right=Constant(value=2)))])Read it as the meaning of the statement. It is an assignment. Its target is the name total in a Store context, so the name is written. Its value is a binary operation: the name price, which is read, multiplied by the constant 2.
Operator precedence is already resolved here. A tree has no brackets and no "do this first": the operation that happens last sits at the top, and its operands hang below it. Tools that read code rather than run it work on this tree: linters, formatters, type checkers. pytest, from the topic Testing, rewrites assert statements by editing the tree before compiling it.
Bytecode and the code object
The compiler walks the tree and emits bytecode: a sequence of simple instructions for a virtual machine. It stores the bytecode, together with everything else the function needs, in a code object, attached to the function as f.__code__. The module dis disassembles it:
import dis
def f(price, qty):
total = price * qty
return total + 1
dis.dis(f)
print(f.__code__.co_varnames, f.__code__.co_stacksize) 3 RESUME 0
4 LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
BINARY_OP 5 (*)
STORE_FAST 2 (total)
5 LOAD_FAST_BORROW 2 (total)
LOAD_SMALL_INT 1
BINARY_OP 0 (+)
RETURN_VALUE
('price', 'qty', 'total') 2Each row is one instruction. On the left is the source line, printed only where it changes. Then come the instruction's name, its opcode, then its argument, and in brackets what the argument means. co_varnames lists the local variables, arguments first. So STORE_FAST 2 (total) refers to total by its position, 2, in that tuple. co_stacksize is the deepest the value stack ever gets in this function, computed by the compiler. RESUME marks the start of the function.
When does this compilation happen? Once, when the whole file is compiled, before anything runs. The body of f becomes a code object stored as a constant of the module. Executing def does not compile anything: an instruction MAKE_FUNCTION wraps the ready code object into a function object and binds it to the name f.
Three names in the listing are recent. LOAD_SMALL_INT (3.14) pushes a small integer stored in the instruction itself. LOAD_FAST_LOAD_FAST (3.13) is a superinstruction: two loads for the price of one. The _BORROW forms (3.14) load a local without touching its reference count. Python 3.13 prints LOAD_FAST_LOAD_FAST, LOAD_FAST and LOAD_CONST 1 (1) in those places. The instruction set is not stable between versions, which is why .pyc files carry the version in their name, such as cpython-314.
The evaluation loop and the value stack
CPython's bytecode runs on a stack machine. Each call of a function gets slots for its local variables and a value stack for intermediate results. The evaluation loop, written in C, fetches an instruction, executes it and moves to the next one. Most instructions pop their operands from the value stack and push their result. Everything Python code does, it does through this loop, one instruction at a time.
The rules for the instructions of f, from the dis documentation:
LOAD_FAST_BORROW ipushes the value of local sloti; the doubled form pushes two.LOAD_SMALL_INT npushes the integern.BINARY_OP oppops two values, applies the operator and pushes the result. The lower of the two is the left operand.STORE_FAST ipops the top value into local sloti.RETURN_VALUEpops the top value and returns it to the caller.
Here is f(3, 4) run instruction by instruction. The arguments are already in their slots: price is 3, qty is 4.
| Instruction | Value stack after it | Slots that change |
|---|---|---|
LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 |
3, 4 | |
BINARY_OP 5 (*) |
12 | |
STORE_FAST 2 (total) |
empty | total = 12 |
LOAD_FAST_BORROW 2 (total) |
12 | |
LOAD_SMALL_INT 1 |
12, 1 | |
BINARY_OP 0 (+) |
13 | |
RETURN_VALUE |
empty | returns 13 |
Between statements the stack is empty. Its deepest point is two values, which is the co_stacksize of 2 from the previous block.
The table also shows why a local variable is cheap. Its name became a slot number at compile time, so reading it is an array access. A global name is different: LOAD_GLOBAL looks it up by name, first in the dictionary of the module, then in the dictionary of built-ins. Every instruction, however small, also pays for the loop itself: fetch, decode, jump to the C code that implements it. How a processor runs that C code is the subject of the course Computer Architecture and Operating Systems.
Frames
The slots and the value stack of a call live in its frame. A frame holds the code object, the local slots, the value stack, the position of the current instruction and a link to the frame of the caller. The chain of these links is the call stack. A traceback prints it, and pdb's where walks it.
From Python, sys._getframe() returns the current frame as an object:
import sys
def inner(n):
frame = sys._getframe()
print(frame.f_code.co_name, frame.f_lineno, list(frame.f_locals))
caller = frame.f_back
print(caller.f_code.co_name, caller.f_lineno)
print(caller.f_back.f_code.co_name)
return n
def outer():
return inner(10)
outer()inner 5 ['n', 'frame']
outer 12
<module>inner stands on line 5, and its locals are n and frame. Its caller outer is waiting on line 12, and below outer lies the frame of the module itself.
Every call gets its own frame, including every call of a recursive function from the topic Functions. That is why each level of recursion has its own n. Since 3.11 frames live in a compact internal form, and the frame object above is created only when something asks for it: sys._getframe, a traceback, a debugger. This made calls cheaper, but a call is still real work. It sets up a frame, copies the arguments into its slots and starts executing a new code object. That is one reason why a function call costs more than an addition.
The specializing interpreter
BINARY_OP 5 (*) does not know what it multiplies. Two integers, two floats, a string and an integer, two NumPy arrays: all are possible. So the generic instruction looks at the types of the operands and calls the __mul__ of the left one, from the topic The data model, or the __rmul__ of the right one. That lookup is most of the cost. Yet in a real program one particular * sees the same types almost every time.
Since 3.11 CPython is a specializing adaptive interpreter. An instruction that can benefit has an inline cache: a little space reserved right after it in the bytecode. After a short warm-up the interpreter looks at the operands it actually saw and rewrites the instruction in place into a form for those types. A specialized instruction first runs a guard, a cheap check that its assumption still holds, for example "both operands are exactly int". Then it takes the shortcut. If the guard fails, the instruction runs the generic operation and counts a miss. After enough misses it specializes again for what it sees now. dis(f, adaptive=True) shows the current bytecode. Continue the script from the block on bytecode:
for _ in range(1000):
f(3, 4)
dis.dis(f, adaptive=True)
for _ in range(1000):
f(2.5, 4.0)
dis.dis(f, adaptive=True) 3 RESUME_CHECK 0
4 LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
BINARY_OP_MULTIPLY_INT 5 (*)
STORE_FAST 2 (total)
5 LOAD_FAST_BORROW 2 (total)
LOAD_SMALL_INT 1
BINARY_OP_ADD_INT 0 (+)
RETURN_VALUE
3 RESUME_CHECK 0
4 LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (price, qty)
BINARY_OP_MULTIPLY_FLOAT 5 (*)
STORE_FAST 2 (total)
5 LOAD_FAST_BORROW 2 (total)
LOAD_SMALL_INT 1
BINARY_OP_EXTEND 0 (+)
RETURN_VALUEAfter calls with integers, the multiplication became BINARY_OP_MULTIPLY_INT; on this build that happened already on the second call. Floats then failed its guard, and after about fifty calls it became BINARY_OP_MULTIPLY_FLOAT. The addition of a float and the integer 1 became BINARY_OP_EXTEND, a 3.14 form for mixed operand types. Attribute reads and calls specialize the same way: p.x on instances of one class becomes LOAD_ATTR_INSTANCE_VALUE, and len(batch) becomes LOAD_GLOBAL_BUILTIN followed by CALL_LEN.
Specialization never changes what a program computes. Code with stable types, which is most code, runs on specialized instructions after a few calls. Code that mixes types at one spot keeps falling back to the generic path.
Reference counts and cycles
The topic Values, types and names said that an object lives as long as something refers to it. CPython implements "as long as" with a reference count in every object. Storing a reference increments it, dropping one decrements it, and the object is freed the moment the count reaches zero. sys.getrefcount returns the count, plus one temporary reference held by its own argument. weakref.finalize registers a function to run when an object is freed, without keeping the object alive:
import sys, weakref
class Batch:
pass
freed = []
a = Batch()
b = a
weakref.finalize(a, freed.append, "batch")
print(sys.getrefcount(a)) # a, b and the argument of getrefcount
del a
print(freed) # b still refers to the object
del b
print(freed) # freed right here3
[]
['batch']del a removes a name, not an object. del b drops the last reference, and the object is freed during that statement. This is also how a NumPy array gives its memory back as soon as its last name disappears. Exact counts are a detail: the borrowed loads of 3.14 can make getrefcount inside a function show less than before, so the examples here run at the top level of a script.
Reference counting cannot free a cycle. Two objects that refer to each other keep both counts above zero after the program drops every name for them. For that CPython has a cycle collector. It examines only containers, such as lists, dicts and instances, and finds groups referenced only from inside the group:
import gc, weakref
class Node:
pass
gc.collect() # start from a clean state
x, y = Node(), Node()
x.other, y.other = y, x # a cycle of two objects
r = weakref.ref(x) # does not keep x alive
del x, y
print(r() is None) # unreachable, but still in memory
print(gc.collect()) # objects the collector found
print(r() is None)
print(gc.get_threshold())False
2
True
(2000, 10, 10)The collector also runs on its own. In 3.14.7 it is generational: new containers start in generation 0, collected once allocations exceed deallocations by 2000; survivors move to older generations, collected less often. Early 3.14 releases shipped a different, incremental collector, and 3.14.5 went back to this one, so thresholds are another version detail.
Immortal objects and the JIT
Some objects are used everywhere: None, True, False, small integers. Updating their counts from every line of every program is wasted work. Since 3.12 such objects are immortal: their count holds a special value that increments and decrements leave alone, and they are never freed. The integers from −5 to 256 are created at start-up and reused, so any result in that range is the cached object:
import sys
print(sys._is_immortal(None), sys._is_immortal(7), sys._is_immortal(10**6))
a = 256; b = int("256")
print(a is b)
a = 257; b = int("257")
print(a is b, a == b)True True False
True
False TrueThis explains a classic bug: comparing numbers with is. It "works" in a test with small numbers and fails with large ones. Use == for values and keep is for identity, which in practice means is None.
The specializing interpreter still pays for dispatch on every instruction. A JIT compiler removes that cost by turning hot code into machine code while the program runs. CPython 3.14 has an experimental one. This build includes it, off by default: sys._jit.is_available() prints True, sys._jit.is_enabled() prints False, and the variable PYTHON_JIT=1 turns it on. The release notes put its effect between 10 % slower and 20 % faster, so measure before you rely on it.
The costs are now visible: a dispatch per instruction, a dictionary lookup per global, a frame per call, an object per intermediate result, a count update per stored reference. The next topic, Writing fast Python, turns them into practice. Measure first, choose the right data structure, cut interpreter overhead in the loop that remains, and move numerical loops out of the interpreter. How processors, memory and machine code work underneath is the subject of the course Computer Architecture and Operating Systems.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.