Read CPython Disassembly
Core idea
Disassembly translates a code object’s instruction encoding into readable records. In CPython, dis.get_instructions returns Instruction objects with fields such as opname, arg and argval. Use the current runtime to inspect operations instead of interpreting raw byte offsets yourself. The instruction set is implementation-specific and may change between releases.
import disdef add(a, b): return a + bfor i in dis.get_instructions(add): if i.opname == 'BINARY_OP': print(i.opname, i.argrepr)print(add(2, 5))In CPython 3.13.5 the generic binary instruction describes addition. The function result is a separate observation.
Expected output:
BINARY_OP +7Inspect source locations
import disdef price(n): return n * 3instructions = list(dis.get_instructions(price))print(all(isinstance(i.offset, int) for i in instructions))print(any(i.positions.lineno is not None for i in instructions))Instructions carry offsets and available source position information; exact offsets are not fixed here.
Expected output:
TrueTrueCommon mistake
Do not infer runtime cost by counting instructions. Fused operations, inline caches and specialization change the relationship between source, instructions and execution.
Practice
Disassemble a conditional function and identify the operations for comparing and returning; record the Python version with your observations.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Disassembly
Check your understanding of disassembly.
What is printed?
import disdef f(a,b): return a*bprint(any(i.opname=='BINARY_OP' for i in dis.get_instructions(f)))What is printed?
import disdef f(): return 3print(type(next(dis.get_instructions(f))).__name__)What is a disassembly?
Are exact offsets stable across CPython releases?