Disassembling CPython Opcodes with dis Module
1Concept
CPython uses a virtual stack machine. Bytecode opcodes manipulate values on the frame's evaluation stack. Opcodes like `LOAD_FAST`, `STORE_FAST`, `BINARY_OP`, and `RETURN_VALUE` execute inside the main C loop.
2Architecture Diagram
CPython Evaluation Stack:
[ LOAD_FAST salary ] ---> [ LOAD_FAST rate ] ---> [ BINARY_OP (Mult) ] ---> [ RETURN_VALUE ]
|salary| |rate| |res| |res|
+------+ |salary| +---+ +---+
+------+3Code Example
Python 3.12
import dis
def multiply(a: int, b: int) -> int:
return a * b
print("=== Bytecode Disassembly for multiply() ===")
dis.dis(multiply)4Expected Output
=== Bytecode Disassembly for multiply() ===
5 0 RESUME 0
6 2 LOAD_FAST 0 (a)
4 LOAD_FAST 1 (b)
6 BINARY_OP 5 (*)
10 RETURN_VALUE5Key Takeaways
- ✓LOAD_FAST reads local variables directly from frame array without dict lookup.
- ✓Python 3.11+ replaced BINARY_MULTIPLY with generalized BINARY_OP opcode.
- ✓RETURN_VALUE pops top of stack and returns control to caller frame.