guide 08 / 08
How the CPython Interpreter Works: A Bytecode Example
See how the CPython interpreter turns code into tokens, an AST, bytecode and results, with a hands-on CPython example using the dis and ast modules.
TL;DR
- CPython runs code in stages: tokenize, parse to an AST, compile to bytecode, evaluate.
- The dis and ast modules let you inspect each stage yourself.
- Bytecode is cached in __pycache__ for imported modules.
- Recent versions add adaptive specialization and an experimental JIT.
01The pipeline at a glance
- Tokenizer: splits source text into tokens (names, numbers, operators).
- Parser: builds an Abstract Syntax Tree (AST) using CPython's PEG parser.
- Compiler: turns the AST into a code object containing bytecode.
- Evaluation loop: executes bytecode instructions one by one in
Python/ceval.c.
02Step 1 & 2: tokens and the AST
import ast
tree = ast.parse("total = price * qty")
print(ast.dump(tree, indent=2))
The output shows an Assign node whose value is a BinOp with Mult. This is the structure CPython's compiler works from. The tokenize module shows the earlier token stage.
03Step 3: bytecode with dis
import dis
def total(price, qty):
return price * qty
dis.dis(total)
You'll see instructions such as LOAD_FAST (push local variables), BINARY_OP (multiply) and RETURN_VALUE. Exact names and layout change between versions, which is one reason bytecode isn't a stable public interface.
04Step 4: the evaluation loop
CPython's evaluation loop reads each instruction and executes it on a value stack. Since Python 3.11, the specializing adaptive interpreter rewrites hot instructions into faster specialized forms, for example a version of BINARY_OP that assumes two integers. Python 3.13 introduced an experimental JIT compiler that later releases continue to develop.
05Where .pyc files fit
When you import a module, CPython saves its bytecode to __pycache__/module.cpython-315.pyc so the next import can skip compiling. The script you run directly isn't cached the same way. Deleting __pycache__ is always safe, because CPython regenerates it.
06Memory management in the loop
Every object carries a reference count. When it drops to zero, CPython frees the object immediately. A cyclic garbage collector periodically finds groups of objects that reference only each other. You can check a count with sys.getrefcount(obj), which reports one extra for the function argument itself.
07The GIL and free-threading, briefly
In the standard build, a thread must hold the Global Interpreter Lock to execute bytecode, so only one thread runs Python code at a time. I/O-bound threads still work well because they release the lock while waiting. The optional free-threaded build removes the GIL and uses finer-grained locking, letting CPU-bound threads run in parallel. It costs some single-thread speed and needs compatible extensions.
08Try it: watch specialization happen
On Python 3.11 and newer, you can see the adaptive interpreter at work:
import dis
def add_all(nums):
total = 0
for n in nums:
total = total + n
return total
for _ in range(1000):
add_all(range(10)) # warm up so CPython specializes
dis.dis(add_all, adaptive=True)
After warming up, some generic instructions show specialized names, such as integer-optimized forms of BINARY_OP. Exact names differ by version. That is the point: these are internal details that CPython is free to change as it gets faster.
09Where to go next
- Read the “Python Language Services” chapter of the docs, which covers
ast,dis,tokenizeandsymtable. - Browse the internals documentation in the repository's
InternalDocs/folder, written by core developers. - Build CPython with
--with-pydebugand step through the evaluation loop in a C debugger. - Follow the “What's New” page for each release to see how the interpreter changes.
10Read the real code
Everything above lives in the repository: Parser/ for the parser, Python/compile.c and Python/codegen.c for compilation, Python/ceval.c and Python/bytecodes.c for execution. Download the source and follow along:
??Quick questions
Q01Is CPython an interpreter or a compiler?
Both. It compiles source to bytecode, then interprets that bytecode.
Q02Does CPython compile to machine code?
Not by default. An experimental JIT can generate machine code for hot paths in recent versions.