Lesson · Python Internals
Bytecode
95 min readBytecode
CPython compiles source to bytecode executed by an evaluation loop. `dis` is useful for learning and diagnostics, but opcode details are implementation- and version-specific.
Learning goals
- Explain what CPython's compile step produces: a code object holding bytecode plus metadata, not machine code.
- Read a
dis.dislisting and say what the offset, opcode, and argument columns show. - Walk through
addwith a stack model: load the operands, apply the operation, return the result. - Check a claim about bytecode against
disoutput for your interpreter instead of assuming an instruction set. - State why an opcode sequence is not a stable language contract across CPython releases.
Mental model
Bytecode is the middle representation: close enough to the source to recognize operations, already compiled into instructions for a stack machine. When you disassemble a function, you are reading that representation, and every conclusion drawn from it is a statement about one CPython version, testable with dis and revisable in the next release.
A stack machine in the middle of the pipeline
one instruction, one stack effect
Mental model
the same mechanism as a compact list
source → AST/compiler → code object/bytecode → CPython evaluation loop
Version note
Bytecode is an implementation detail and changes across Python releases. Always treat opcode examples as version-specific.
Core idea
CPython executes Python by compiling source to bytecode first, then running that bytecode in an evaluation loop, and dis exposes the compiled form so you can watch how expressions decompose into instructions. Bytecode sits between the two extremes: operations are already chosen, but the loop still interprets each instruction, so it is neither source nor machine code. Everything learned from a listing is true of the interpreter that produced it, which is why the version matters.
Python bytecode
Python bytecode is the compact instruction set CPython's compiler emits for a module or function, stored inside a code object together with metadata such as names and constants. The evaluation loop executes those instructions one by one, pushing and popping references on a stack, which is why identical source can produce different listings across CPython versions. Bytecode is an implementation detail of CPython, not a contract of the Python language.
dis
dis displays CPython bytecode instructions for functions and code objects. Use it to understand execution mechanics, but never depend on a specific opcode sequence as a stable language contract.
Stack-machine intuition
A stack-machine model explains many bytecode sequences as pushes of operands followed by operations that consume them and push results. Exact CPython execution internals evolve by version.
Code objects
A code object is an immutable compiled description of executable Python code, including bytecode and metadata. A function object adds globals, defaults, annotations, and closure references.
Implementation-specific details
Opcode names, argument layouts, and specialization behavior are CPython specifics that change between releases: 3.11 introduced an adaptive interpreter that rewrites instructions at runtime, and later releases adjusted instruction sets further. Use dis to inspect the interpreter you are running, and never build behavior that depends on a particular sequence of opcodes.
Walkthrough
dis.dis(add)prints the instructions inadd's code object; each line shows an offset, an opcode name, and its argument, with the resolved name in parentheses when there is one.- The body
return a + bcompiles to two loads and an operation, something likeLOAD_FAST 0 (a),LOAD_FAST 1 (b),BINARY_OP 0 (+)(exact offsets and spellings vary by version), followed byRETURN_VALUE. - Stack view: each
LOAD_FASTpushes one object,BINARY_OPpops two, performs the addition, and pushes the result, andRETURN_VALUEpops that result and ends the call, which is the whole evaluation model for this function. - Predict before running: how many instructions you expect for
return a + b, and how many values sit on the stack just beforeRETURN_VALUEruns.
Experiments to try
- Disassemble
def add(a, b): return a + banddef add(a, b): return b + aand diff the listings; identify which instructions changed and which stayed. - Add a third parameter with a default to
addand check how the signature appears in the code object's metadata throughdis. - Compare the listing for
x = 1at module level, inside a function, and inside a class body; note where you seeSTORE_NAMEversusSTORE_FAST. - Disassemble a lambda and find its separate code object nested in the output; confirm it is a distinct code object with
dis.dis(lambda_obj.__code__).
Playable lesson
Lab: Bytecode stack machine
Display source, current bytecode instruction, and a conceptual evaluation stack. Mark opcode details as CPython and version specific.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Bytecode stack machine
Source
def add(a, b):
return a + bInstructions
- 0RESUME 0bookkeeping for the frame
- 2LOAD_FAST apush the local named a
- 4LOAD_FAST bpush the local named b
- 6BINARY_OP +pop two, push one result
- 8RETURN_VALUEpop the result and return it
Operand stack
- empty
nothing yet: the frame is being prepared
Locals
- a3
- b4
Opcodes, their names and their offsets are CPython implementation details, version specific.
Predict first
A call is starting. How many items are on the frame's evaluation stack?
`dis` shows what the compiler produced: a short list of instructions, each doing one small thing to a stack. The offset column is where the next instruction lives, and jumps are expressed as those offsets.
One instruction, one stack effect: push, operate, return.
Common mistakes
- Reading a listing as a promise: opcode names such as
LOAD_FASTandBINARY_OPare CPython details that can be renamed, split, or fused between releases. - Comparing listings from two interpreters without checking versions: the same source produces different instruction sets on different CPython releases.
- Assuming one source line equals one instruction: a single expression expands into several instructions, so a short line can produce a dozen ops.
- Treating instruction count as a performance oracle: each opcode's cost differs, and the adaptive interpreter specializes hot instructions at runtime, so fewer listed instructions do not automatically mean less time.
Practice: Easy
- Run the worked example and copy the listing for
add; label each instruction as push, operate, or return in the stack model. - Disassemble
addandmul = lambda a, b: a * b; list which instructions they share and which one differs. - Change
addtodef add(a, b=1): return a + b + 1and note how the listing grows; state how many values are on the stack before the final return.
Practice: Medium
- Disassemble two functions that compute the same result in different styles (a
forloop versussum), compare listing lengths, and check with a timing run whether listing length predicts speed. - Compare the module-level and function-local listings for the same assignment
x = 1(STORE_NAMEversusSTORE_FAST) and explain why local access is cheaper at runtime. - Write a function with an
if/elseand locate the jump instruction; draw the control flow as offsets and jumps instead of source lines.
Practice: Hard
- Predict the full listing of a function you wrote, instruction by instruction, then diff your prediction against the real
disoutput and explain every miss. - Extract a function's code object and inspect
co_names,co_varnames, andco_consts; explain what each field adds to the instruction listing. - Describe how the evaluation loop keeps a per-frame operand stack while
addruns, using the two loads and the operation as the example; state where the result ofBINARY_OPlives just before the return.
Lesson checklist
- I can explain the path from source to bytecode to evaluation loop in one sentence.
- I can read a
dislisting and say what the offset, opcode, and argument columns hold. - I can walk
a + bas two pushes, one operation, and a return on a stack. - I can state why bytecode observations must name the CPython version they came from.
Remember
CPython turns source into bytecode held in a code object, then a stack-based evaluation loop executes it instruction by instruction. `dis` makes that middle layer visible: two loads and an operation for `a + b`, with the exact names and argument formats belonging to your interpreter's version. Read listings as explanations of behavior, not as stable contracts, and check differences against the installed version instead of assuming them.
Interview angles
What is the main purpose of **Python bytecode**?+
Python bytecode is the compact instruction set CPython's compiler emits for a module or function, stored in a code object with metadata such as names and constants. The evaluation loop executes it instruction by instruction on a stack, and it counts as a CPython implementation detail rather than a language contract.
What should you pay attention to when using **dis**?+
dis displays CPython bytecode instructions for functions and code objects. Use it to understand execution mechanics, but never depend on a specific opcode sequence as a stable language contract.
How does **Stack-machine intuition** fit into this lesson?+
A stack-machine model explains many bytecode sequences as pushes of operands followed by operations that consume them and push results. Exact CPython execution internals evolve by version.
Why is "this snippet has fewer bytecode instructions, so it is faster" a weak argument?+
Instruction counts ignore each opcode's cost, the adaptive interpreter can specialize hot instructions at runtime, and instructions can be fused or split between releases. Measure the snippet; treat the listing as an explanation you verify, not a performance prediction.