The Canon / R7 · Import is code execution / Lesson 22

From text to bytecode

Nine phases between python script.py and the first executed instruction: process launch, interpreter startup, tokenizer, parser, AST, symbol table, compiler, code object, cache. Each one can be invoked by hand to see what it produced.

L1 · 12 minL2 · 12 min📱 phoneverified · CPython 3.11.15, linux x86-64

1Predict

Commit to an output and a reason before you open the answer.

Snippet A
import sys
print(len(sys.modules))
print(sum(1 for m in sys.modules.values()
          if getattr(getattr(m, '__spec__', None), 'origin', None) == 'frozen'))
34
14
Thirty-four modules are already loaded before your first line, fourteen of them built into the interpreter binary. There cannot be zero: the import mechanism itself is a module.
Snippet B
code = compile("z = [1, 2, 3]", "<s>", "exec")
print(code.co_consts)
((1, 2, 3), None)
The constants hold a tuple, although the source has a list. A list is mutable and cannot be a constant — the compiler stores an immutable prototype and expands it into a list with an instruction.
Snippet C
import io, tokenize
src = "def f():\n    return 1\n"
for t in tokenize.generate_tokens(io.StringIO(src).readline):
    print(tokenize.tok_name[t.type], repr(t.string))
NAME 'def'
NAME 'f'
OP '('
OP ')'
OP ':'
NEWLINE '\n'
INDENT '    '
NAME 'return'
NUMBER '1'
NEWLINE '\n'
DEDENT ''
ENDMARKER ''
INDENT and DEDENT are real tokens, on a par with brackets. Indentation in Python is not formatting: it goes into the token stream and takes part in the grammar.
Snippet D
DEBUG = False

def handle(verbose):
    if verbose:
        DEBUG = True
    if DEBUG:
        return "verbose"
    return "brief"

print(handle(True))
print(handle(False))
verbose
UnboundLocalError: cannot access local variable 'DEBUG'
where it is not associated with a value
One branch works, the other fails. The decision that DEBUG is a local variable is made at compile time, for the whole function at once, before anything has run.

2Mechanism

Between “pressed Enter” and “the first instruction ran” there are nine distinct phases. None of them is hidden: each has a module in the standard library that lets you invoke it on its own and look at the result. Below is the whole pipeline in order, with numbers taken on this machine.

Python is compiled. Not into machine code but into bytecode for a stack virtual machine — yet it goes through a full compiler: lexer, parser, intermediate representation, optimizations, code generation.

Compilation happens not “ahead of time” but on first import — and its result is cached in .pyc. Everything else follows from this: the startup time, __pycache__, and the fact that a syntax error in a module nobody imports does not stop the program from working.

Phase 0 · the process

The kernel starts /usr/bin/python3 with an ordinary execve. The dynamic loader pulls in libpython3.11.so (or it is compiled in statically), and control goes to main() in Programs/python.c — a twenty-line file whose whole job is to call Py_BytesMain.

From the OS's point of view Python is an ordinary C program. There is no JVM-style virtual machine with a separate host process: the interpreter is a library linked to a tiny main.

Phase 1 · interpreter initialization

Modules/main.c parses the arguments and builds the configuration, after which Python/pylifecycle.c brings the interpreter up. The order here is not accidental — it solves a chicken-and-egg problem:

launchtimemodules in sys.modules
python -c pass13.9 ms34
python -S -c pass9.5 ms23
python -c "import json"22.1 ms—
python -c "import numpy"101.6 ms—

Four and a half milliseconds is the price of site.py. Eighty-eight is the price of a single import numpy. For a command-line utility called in a loop from a shell script, this is its performance.

Phase 2 · reading the source

The file is read as bytes and decoded. UTF-8 by default; PEP 263 allows declaring another encoding with a # -*- coding: cp1251 -*- line in the first two lines, and the tokenizer reads it before it starts parsing. A BOM is recognized too.

This is the only phase where Python sees bytes. Everywhere after that it is str, that is, the sequence of code points from lesson 02.

Phase 3 · the tokenizer

Parser/tokenizer.c turns the text into a stream of tokens. The main peculiarity is visible in snippet C: indentation becomes tokens. The tokenizer keeps a stack of indentation levels and on every line compares the current one with the top of the stack — deeper produces INDENT, shallower produces one DEDENT for each level popped.

Hence three consequences that are usually considered quirks:

Phase 4 · the parser

Since 3.9 (PEP 617) CPython has a PEG parser instead of the old LL(1). The grammar lives in Grammar/python.gram, and Parser/parser.c is generated from it — a file of tens of thousands of lines that nobody writes by hand.

The practical difference between PEG and LL(1): the parser can try an alternative, backtrack and try the next one. This removed grammatical restrictions that used to make some syntax inexpressible, and gave dramatically better error messages — “Perhaps you forgot a comma?” appeared precisely because the parser can parse a failed branch to the end and understand what was missing from it.

Phase 5 · AST and constant folding

The parser produces a tree. The ast module hands out that same tree as Python objects — literally the same tree, not a separate implementation.

The tree is processed by Python/ast_opt.c — an optimizer that computes whatever can be computed right away. Hence snippet B, and this:

import ast
print(ast.dump(ast.parse("x = 1 + 2"), indent=2))
# the tree will keep a BinOp: folding happens later, in the compiler

code = compile("x = 1 + 2\ny = 'ab' * 3", "<s>", "exec")
print(code.co_consts)
# → (3, 'ababab', None)

The constants already hold the finished values: there will be no addition or multiplication at execution time. The optimizer is careful — it will not fold 'a' * 10**9, so as not to blow the .pyc up to a gigabyte.

Phase 6 · the symbol table — the most underrated one

Python/symtable.c makes a separate full pass over the tree before a single instruction is generated. Its only task is to decide, for every name in every scope, what it is: local, global, cell (a variable captured by a nested function) or free (captured from an enclosing one).

import symtable
code = '''
g = 1
def outer():
    a = 1
    def inner():
        nonlocal a
        b = g
        return a + b
    return inner
'''
st = symtable.symtable(code, "<s>", "exec")
outer = st.get_children()[0]
inner = outer.get_children()[0]
for s in inner.get_symbols():
    print(s.get_name(), "local" if s.is_local() else "",
          "global" if s.is_global() else "", "free" if s.is_free() else "")
# → a   free
# → b  local
# → g   global

The rule is simple and static: a name that is assigned anywhere in a function is local throughout that function. Not from the moment of assignment — everywhere, including the lines above it. There is no control-flow analysis here.

Snippet D follows from this one rule: handle contains the line DEBUG = True, so DEBUG is local for the whole function, so if DEBUG reads the local. With verbose=True it has been assigned by that point, with verbose=False it has not. global and nonlocal come from here too: they are not “runtime modifiers” but instructions to this phase, the only way to override its decision.

And this is also why scopes in Python are lexical and static, even though types are dynamic. A type is unknown until execution; which scope a name belongs to is always known.

Phase 7 · the compiler

Python/compile.c walks the tree, knowing the symbol table's decisions, and builds a control-flow graph of basic blocks. Optimizations like “remove an unreachable block” and “collapse a chain of jumps” are done on the graph, after which the blocks are laid out into a linear stream of bytes.

At the same time three auxiliary structures are computed:

Phase 8 · the code object

The result of compilation is a code object, an ordinary immutable Python object. It can be obtained, taken apart, passed around, saved.

def demo(a, b=2, *args, kw=3, **kwargs):
    total = a + b
    for x in args:
        total += x
    return total

co = demo.__code__
print(co.co_argcount, co.co_kwonlyargcount, co.co_nlocals, co.co_stacksize)
# → 2 1 7 3
print(co.co_varnames)
# → ('a', 'b', 'kw', 'args', 'kwargs', 'total', 'x')
print(len(co.co_code), "bytes of bytecode")
# → 36 bytes of bytecode

Note the order in co_varnames: positional arguments first, then keyword-only, then *args and **kwargs, and only then the real locals. The order is fixed by the compiler, and it is how the LOAD_FAST 0 instruction knows that zero is a. Names take no part in execution: access to a local variable is an index into an array, not a dictionary lookup.

This is a direct consequence of phase 6. Locals are fast precisely because the symbol table decided everything in advance.

Phase 9 · the .pyc cache

There is no point compiling the same module on every run, so the code object is serialized through Python/marshal.c and put into __pycache__. The format is almost indecently simple: a sixteen-byte header followed by marshal data.

import struct, marshal, importlib.util, os
import json                                  # anything from the standard library

raw = open(json.__cached__, "rb").read()
magic, flags, mtime, size = struct.unpack("<4sIII", raw[:16])
print(magic.hex(), flags, mtime, size)
print(importlib.util.MAGIC_NUMBER.hex())     # the same magic
obj = marshal.loads(raw[16:])
print(type(obj).__name__)
# → code
fieldbytesmeaning
magic0–3The bytecode format version. It changes almost every release — which is why a .pyc from 3.10 is simply ignored
flags4–70 — validation by timestamp, 1 — by source hash (PEP 552)
mtime8–11The source's modification time at the moment of compilation
size12–15The size of the source in bytes

Validation by default compares mtime and size, not content. The practical consequence: if code is deployed so that the file's modification time ends up older than the one recorded in the cache, the old bytecode will run. That is exactly why builds that care about reproducibility turn on hash-based .pyc (py_compile --invalidation-mode checked-hash).

A measurement on a module of 1199 lines: the first import with compilation takes 23 ms, a repeat with a ready cache 14 ms. Compilation itself costs 9 ms, and that is exactly what every process pays when __pycache__ is not writable — a container with a read-only file system, for example.

3Limits of the model

Where this stops holding

Not all code goes through phase 9. exec, eval, compile and code from the REPL are compiled from scratch every time — there is no cache for them and there cannot be, because there is no file. A string assembled in a loop and passed to eval is compiled in full on every iteration.

The compilation mode changes the result. compile(src, name, "exec"), "eval" and "single" give different bytecode for the same text: single is the REPL mode, it adds printing of the expression's result. Hence the difference between “pasted it into a file” and “pasted it into an interactive session”.

The -O and -OO flags change the bytecode. The first throws out assert and code under if __debug__, the second also docstrings. The cache is then stored under a different name (.opt-1.pyc), so the versions cannot be mixed up, but code whose correctness depends on assert breaks silently.

The entire content of this chapter is an implementation detail 🔧. Not a single opcode, nor the size of a code object, nor the .pyc format is part of the language. In 3.12 the pipeline is already different: the interpreter is generated from Python/bytecodes.c, block linearization was reworked, the instruction set is different. What is guaranteed is the semantics, not the path to it.

4Root

The chapter unfolds R7 · import is code execution downwards, into the mechanics. The statement “a module executes once per process” means at this level: phases 2–8 are run once, the result goes into sys.modules, and phase 9 carries it across processes as well.

From here you can also see why Python has no linking phase. In C the linker resolves function names and writes the addresses into the binary. Here there are almost no names in the bytecode — there are indices for locals and strings in co_names for everything else, and binding happens on every access, at runtime. This is R2 seen from the compiler's side: there is nothing to bind in advance, because there is nothing to bind it with.

And third: phase 6 shows the boundary between static and dynamic in Python more precisely than any definition. Scope is decided statically, type dynamically. The first gives fast local variables and UnboundLocalError; the second gives R8 — the impossibility of sound type inference.

5Analogy

The most precise analogy is building a C project without linking.

gcc -c file.c gives file.o: machine code with holes where the external names go. Then the linker fills the holes with addresses. Python has the first half and not the second: a code object is the same kind of “object file”, with strings where the addresses would be, and the holes are filled every time an instruction executes.

__pycache__, meanwhile, behaves like make, with one caveat: make checks dependencies, Python checks only the file itself. Change a module that another depends on, and the second one is not recompiled, because its own mtime has not changed. Nor does it need to be: binding happens at runtime anyway.

Hence a practical conclusion familiar to anyone who has suffered with make clean: in Python there is no “stale build” caused by dependencies. There is a stale one caused by the mtime of the file itself — and that is the only scenario worth keeping in mind.

6Questions a careful reader asks

Questions that come up on their own if you read closely. The answer is under the question.

If Python is compiled, why is it called interpreted?

Both are compiled. The difference is who the result is addressed to: C++ produces machine code that the processor executes, Python produces bytecode that another program executes. And Python cannot produce machine code because the type of the operands is unknown until execution: there is nothing to compile a + b into a machine addition instruction from.

Next — why the question itself is badly posed.

This pair of words mixes two different questions, and “compilation” means two different things.

The first meaning is translating the source into another representation. Python does that, and this whole chapter is about it. The second is translating into the target machine's code, ahead of time, producing a standalone artifact. Python does not do that.

The real distinguishing question sounds different: who executes the result — hardware or a program? After gcc the processor executes the result. After compile() another program executes it — the evaluation loop from lesson 23. On this axis Python is interpreted, and that is the only sense in which the statement is true.

And the property is attributed to the wrong thing. The language specification says not a word about it: “compiled” and “interpreted” are characteristics of an implementation, not of a language. Nuitka compiles Python to C, and since 3.13 CPython has a JIT. And conversely, there are C interpreters — Cling, tcc -run. Nobody says that C has become interpreted.

Add to this that almost nothing “interpreted” interprets text. Ruby, Lua, JavaScript, Java — all compile to an intermediate representation. Direct interpretation of source died out along with early BASIC. So the popular meaning of the word describes implementations that no longer exist.

The precise formulation that replaces the whole pair: the issue is not compilation versus interpretation but early binding versus late binding. In C the linker resolves names and bakes in the addresses. In Python a name is resolved on every access — that is R2. A late-binding language cannot be compiled in the C sense not because nobody has written a compiler, but because there is nothing to bake in.

So nothing at all is caught before running?

Something is — but only what concerns syntax, and only in the modules that are actually imported.

A module is compiled in full before its first line executes. It is easy to check:

# selfbad.py
print("first line")
print("second")
def bad(:
    pass
$ python3 selfbad.py
    def bad(:
            ^
SyntaxError: invalid syntax

Neither of the two prints ran. This is the behaviour of a compiled language, exactly the same as with gcc.

But a broken module that nobody imports will never show up — because phases 2–8 were simply never run for it. Hence the classic “it crashed in production on a rare path that was not in the tests”.

What is not caught: typos in names, nonexistent attributes, type mismatches. Not because of interpretation, but because the pipeline has no type-checking phase — that is R8. It can be added as a separate tool (mypy), but it cannot be built into the pipeline, and lesson 18 explains why.

Can you ship only the .pyc and hide the sources?

You can ship it; you cannot hide anything.

Technically it works: put mod.pyc alongside (in the legacy layout, not in __pycache__), delete mod.py — the import will go through.

import py_compile, os, pathlib

pathlib.Path("mod.py").write_text('''
SECRET = "can you see me"
def f(): return SECRET
''')
py_compile.compile("mod.py", cfile="mod.pyc")
os.remove("mod.py")

import sys; sys.path.insert(0, ".")
import mod
print(mod.f())
# → can you see me      ← no source, the module works

And now what this is usually done for:

raw = open("mod.pyc", "rb").read()
print("can you see me".encode() in raw)   # → True
print(b"SECRET" in raw)               # → True

All string literals and all names lie in the .pyc in plain text — they have to be there, because co_names and co_consts are needed at execution time. On top of that there are decompilers that recover readable Python from bytecode almost without loss: the control structure is preserved in the bytecode, and the variable names lie in co_varnames.

The upshot: shipping .pyc adds exactly one barrier — “you cannot open it in an editor”. It does nothing to protect against a person who really needs to look. And it ties the shipment rigidly to a minor Python version: the magic in the header changes every release.

Then why can't a Python program be built into a single binary, like in Go?

It can, and people do it — but what you get contains a whole interpreter inside.

Two different approaches, and both run into the same thing:

PyInstaller, PyOxidizer. No compilation at all: they pack the interpreter, the standard library, your bytecode and the dependencies into one file. It is an archive with an unpacker. The size is tens of megabytes; startup is plus the time to unpack.

Nuitka. Real compilation: it turns Python into C and builds it with a compiler. But the generated C is not “your algorithm in C” — it is a sequence of CPython API calls doing exactly what the evaluation loop would have done. So the binary is linked with libpython, and the speed-up is usually within tens of percent, not multiples.

Why it cannot be otherwise. To compile a + b into a machine addition instruction, the compiler has to prove that a and b are numbers of a specific type. In Python this cannot be proven: the type is determined at the moment of access (R2), and any C extension can swap out anything on an object (R6). What remains is to generate code that checks types at runtime and chooses the operation — that is, exactly an interpreter, only unrolled into a straight line.

Go compiles into a standalone binary not because its authors are more diligent, but because types there are known statically. This is not a difference in the quality of implementation; it is a difference in what the language promises.

If bytecode is an implementation detail, why is dis in the standard library?

Because “not guaranteed” and “not shown” are different things, and Python consistently chooses the former over the latter.

dis, symtable, ast, marshal are open not because their behaviour is promised, but because closing them would be pointless: debuggers, profilers, coverage, linters and codemod tools stand on them. Hiding the pipeline would kill that whole layer.

The price of openness is paid regularly: every release breaks the tools that parse bytecode. That is exactly why dis._inline_cache_entries and dis._specialized_instructions are named with an underscore — “look, but don't complain”.

Here the canon's general principle is visible in pure form: the mechanism is shown, there is no promise about it. Exactly the boundary that the 🔒 · 🔧 · 🕳 scale marks, and exactly the skill it trains — telling “I can see this” apart from “I can rely on this”.

Bottom line. There are nine phases between python script.py and the first instruction. The process starts as an ordinary C program; the interpreter brings up built-in and frozen modules, because the import mechanism is itself written in Python and there is nothing to import it with — 34 modules and 13.9 ms before your first line, 4.5 ms of them on site.py. Then the source is decoded, the tokenizer turns indentation into real tokens, the PEG parser builds a tree, and the optimizer folds constants. Then comes the most underrated phase: the symbol table, in a separate pass, decides for every name whether it is local or global — statically, for the whole function at once, without control-flow analysis. Hence UnboundLocalError, hence global and nonlocal, hence fast local variables as an index into an array instead of a dictionary lookup. The compiler builds a graph of basic blocks and lays it out into bytecode, computing the stack depth, the line table and the exception table along the way. The result is an ordinary immutable code object, which marshal puts into a .pyc under a sixteen-byte header, and it is validated by modification time and size, not by content. The whole pipeline is a 🔧 implementation detail: what is guaranteed is the semantics, not the path to it.
From here on — optional
counterfactualC, Java, JavaScript — three other answersCompile once, compile to JVM bytecode, compile on every page load

C and C++. Compilation is completely separate from execution: preprocessor, compiler, assembler, linker — and the output is machine code with the addresses already filled in. An error in an unused function is caught before running; in Python a syntax error in a module nobody imports will never show up. The price is symmetrical: changing one line requires a rebuild and a restart, while in Python the module recompiles itself, unnoticed.

Java. The closest: javac produces bytecode in .class, and the JVM executes it. But compilation there is an explicit build step, and .class is part of the artifact, not a cache. In Python a .pyc can be deleted at any moment without consequences: it is an optimization, not a result.

JavaScript. No cache between runs — the engine parses and compiles the source on every load. Hence the whole front-end toolchain for minification: there the size of the source directly affects startup time. Python solved this problem with .pyc — and that is why nobody in Python cares about the length of variable names.

🐛 reviewAn UnboundLocalError that passes reviewThe tests are green, only the second branch fails — and only in production

A debug flag that is switched on by a condition. It reads perfectly, passes review, passes the tests.

DEBUG = False

def handle(request, verbose=False):
    if verbose:
        DEBUG = True              # ← “let's turn on verbose mode”
    if DEBUG:
        log_everything(request)
    return process(request)

What happens. The assignment DEBUG = True in the function body makes the name local for the whole function — the decision is made by the symbol table at compile time, before any execution. The line if DEBUG reads the local variable. With verbose=True it has already been assigned and everything works; with verbose=False — UnboundLocalError.

Why it passes review. To the eye it reads as “a global flag that we sometimes override”. The module-level DEBUG = False right above the function strengthens the illusion. And the tests for verbose mode are written first — and they are green.

Check it in ten seconds:

import dis
dis.dis(handle)
# Look for LOAD_FAST DEBUG instead of LOAD_GLOBAL DEBUG.
# Faster still:
print(handle.__code__.co_varnames)   # if DEBUG is here, it is local
print(handle.__code__.co_names)      # if DEBUG is here, it is global

How to fix it. Not with global — a global flag changed from a request handler is a bug in itself, especially with the threads from lesson 19. The right way is not to touch global state: if verbose or DEBUG: and no assignment at all.

The general rule. Assigning a name anywhere in a function makes it local everywhere in that function. The only way to read this from the code is co_varnames versus co_names.

⚡ 7.5×Lazy import: 105 ms versus 14A command-line utility that spends all its time on a module it usually does not need

A typical CLI: one heavy command, a dozen light ones, and import numpy at the top of the file.

# cli_eager.py — import at the top
import sys
import numpy as np              # needed only for the "stats" command

def main(argv):
    if argv[1:2] == ["stats"]:
        print(np.arange(10).mean())
    else:
        print("usage: cli [stats]")

main(sys.argv)
# cli_lazy.py — import where it is used
import sys

def main(argv):
    if argv[1:2] == ["stats"]:
        import numpy as np       # pay only when it is really needed
        print(np.arange(10).mean())
    else:
        print("usage: cli [stats]")

main(sys.argv)
commandimport at the topimport where used
ordinary (usage)105 ms14 ms
heavy (stats)112 ms115 ms

Seven and a half times on the frequent path and a three-millisecond penalty on the rare one. The reason comes straight from phase 1: a top-level import is code execution at process startup, not a declaration of a dependency.

Where to look, without guessing:

python -X importtime -c "import myapp" 2>&1 | sort -k2 -nr | head -15

The second column is the module's own time, the third includes nested imports. The line at the very top is the answer.

When it is justified. Command-line utilities, serverless functions with a cold start, any process that is started more often than it works. For a long-lived service the gain is zero — the process starts once there, and a lazy import only adds unpredictability: the heavy module will load on the first request instead of at startup.

What not to do. Do not move everything into functions on principle: an import inside a function checks sys.modules on every call, which is cheap but not free, and readability suffers noticeably. Move only what -X importtime has pointed at.

💻 terminalCheck it in the terminalEvery phase can be invoked by hand: tokenize, ast, symtable, dis, marshal

The whole pipeline is available from the standard library. Run it phase by phase and compare with your prediction.

import io, tokenize, ast, symtable, dis, marshal, struct

SRC = '''
DEBUG = False
def handle(verbose):
    if verbose:
        DEBUG = True
    return DEBUG
'''

# phase 3 — tokens
for t in list(tokenize.generate_tokens(io.StringIO(SRC).readline))[:12]:
    print(tokenize.tok_name[t.type], repr(t.string))

# phase 5 — the tree
print(ast.dump(ast.parse("x = 1 + 2"), indent=2))

# phase 6 — who is local, who is global
st = symtable.symtable(SRC, "<s>", "exec")
fn = st.get_children()[0]
for s in fn.get_symbols():
    print(s.get_name(), "local" if s.is_local() else "global")

# phases 7–8 — bytecode and the code object
code = compile(SRC, "<s>", "exec")
handle_co = [c for c in code.co_consts if hasattr(c, "co_code")][0]
print(handle_co.co_varnames, handle_co.co_names)
dis.dis(handle_co)

Questions for the result: why did DEBUG end up in co_varnames and not in co_names? Which instruction reads it — LOAD_FAST or LOAD_GLOBAL? What changes if you add the line global DEBUG to the function?

And separately — what compilation costs:

import timeit, pathlib, json
src = pathlib.Path(json.__file__).read_text()
print(timeit.timeit(lambda: compile(src, "json.py", "exec"), number=100) / 100 * 1000, "ms")
# That is what every process pays when __pycache__ is not writable.
sourceWhere it lives in real codetokenize, ast, symtable, dis, py_compile — five modules that hardly anyone opens

Lib/tokenize.py. A pure-Python tokenizer compatible with the C one. Useful not in itself but for tools: every linter, formatter and codemod starts with it, because it keeps the comments and whitespace that the AST loses.

Lib/ast.py. ast.NodeTransformer — thirty lines on which all automated code migrations stand. It is worth reading ast.unparse: it shows exactly what the tree does not keep — comments, quotes, parentheses added for readability.

Lib/symtable.py. A thin wrapper over phase 6. The only way to see the compiler's decision about a name without reading bytecode. Useful when arguing about whether a variable is local or not.

Lib/dis.py. Besides dis.dis, there is dis.get_instructions, which gives a structured stream, and dis._parse_exception_table, which shows the exception table from phase 7.

Lib/py_compile.py and Lib/compileall.py. The second is what warms up __pycache__ in a docker image so that compilation is not paid on every container start. One line in a Dockerfile that saves tens of milliseconds on every launch.

Lib/importlib/_bootstrap_external.py. This is where the _validate_timestamp_pyc function lives — the very twenty lines that decide whether to trust the cache or recompile. It reads in a minute and answers every question about __pycache__.

L2What is in a code object and in a .pyc, byte by byte36 bytes of bytecode, 42 bytes of line table, 269 bytes of cache for 33 bytes of source

The code object in full. Everything needed to execute the function, except its current state:

fieldvalue for demowhat for
co_argcount2How many positional parameters it takes
co_kwonlyargcount1How many keyword-only ones
co_nlocals7The size of the locals array allocated on a call
co_stacksize3The maximum depth of the value stack, computed statically
co_flags15OPTIMIZED | NEWLOCALS | VARARGS | VARKEYWORDS
co_varnames7 namesOnly for debugging: execution works by index
co_names—Names that will have to be looked up at runtime
co_consts(None,)Constants, including nested code objects
co_code36 bytesThe instructions themselves
co_linetable42 bytesA compressed “offset → line” map. Larger than the bytecode itself
co_exceptiontable0 bytesEmpty: the function has no try

The line table here is larger than the bytecode — 42 against 36. That is the price of readable tracebacks, and in 3.11 it was deliberately increased for the sake of precise columns in error messages (PEP 657): now the caret under an expression points at a specific operand.

Nesting. A function's code object lies in the module's co_consts. A nested function lies in the outer one's co_consts. The whole tree of a module is serialized with one marshal call:

code = compile("def outer():\n    def inner(): pass\n    return inner", "<s>", "exec")
outer = [c for c in code.co_consts if hasattr(c, "co_code")][0]
inner = [c for c in outer.co_consts if hasattr(c, "co_code")][0]
print(code.co_name, "→", outer.co_name, "→", inner.co_name)
# → <module> → outer → inner

Cache size. A two-line module (VALUE = 42 and a one-line function), 33 bytes of source, gives a 269-byte .pyc — eight times larger. The reason: object headers, line tables and names in every code object. For the standard library the ratio is better, but __pycache__ is still usually bigger than the sources, and in slim docker images that is a noticeable amount.

Constant folding in numbers. The AST optimizer folds arithmetic, concatenation and string repetition, but with a limit on the size of the result:

print(compile("x = 'a' * 100", "<s>", "exec").co_consts)
# → ('aaaa...', None)   — folded
print(compile("x = 'a' * 10**9", "<s>", "exec").co_consts)
# → ('a', 1000000000, None)  — not folded, otherwise the .pyc would be a gigabyte
L3Where this is in the CPython sourcesA file for every phase, all on tag v3.11.15

A rare case where the sources can be read in order: the pipeline is linear, and each phase corresponds to one file.

phasefile
0 · entryPrograms/python.c — twenty lines
1 · configurationPython/initconfig.c, Modules/main.c
1 · bring-upPython/pylifecycle.c — Py_InitializeFromConfig, and Py_FinalizeEx for lesson 23 is there too
1 · frozenPython/frozen.c — the list of built-in modules
3 · tokensParser/tokenizer.c — look for the indentation stack in tok_get
4 · grammarGrammar/python.gram — reads like EBNF
4 · parserParser/pegen.c — the engine; Parser/parser.c — the generated one
5 · foldingPython/ast_opt.c — the whole file is about constants
6 · symbolsPython/symtable.c — the comment at the top explains the phase better than any article
7 · compilerPython/compile.c — the largest file in the pipeline
8 · code objectInclude/cpython/code.h, Objects/codeobject.c
9 · marshalPython/marshal.c — the serialization format, one byte per type

Where to start if you open one file. Python/symtable.c: the forty-line comment at the top sets out phase 6 in full, and after it UnboundLocalError, global and nonlocal stop being three separate facts.

What changed after 3.11. In 3.12 the interpreter is generated from Python/bytecodes.c — a file in a domain-specific language from which the evaluation loop, the tables and the opcode documentation are all built. If you read main, the structure will be different; everything described here refers to 3.11.

connectionsWhere this leadsL17, L08, L04, L12 · and lesson 23 right after
L17 · Import, end to end — what happens to the finished code object next: sys.modules, the order of execution, circular imports. This chapter is its ground floor.
L08 · Functions, closures, decorators — cells and free variables, which appeared here as a decision of phase 6. There you can see what that decision turns into at execution time.
L04 · obj.x, end to end — the co_names from phase 8 are exactly the names that will have to be looked up by the procedure from lesson four. Locals are fast because they were resolved here.
L12 · Context managers and exceptions — the co_exceptiontable from phase 7 explains why in 3.11 try stopped costing anything at all. The mechanics are in lesson 23.
L23 · The execution machine — the direct continuation: what happens to this code object when it starts executing.
readingFurther readingGreen Tree Snakes 🟥 · PEP 617 🟧 · PEP 552 🟦 · devguide 🟧

Written by · The Python Canon