Reading Python Bytecode with the dis Module
This article explains how CPython compiles functions into bytecode, how the dis module makes it readable, and which performance claims derived from bytecode still hold once they are measured on a modern interpreter.
The present article addresses bytecode, the intermediate form into which CPython translates every function before running it, and the module dis, which makes that form readable. Between the source code that a programmer writes and the result that appears on the screen there is a compilation step that usually goes unnoticed. Observing it explains several pieces of folk wisdom about Python performance and, more importantly, shows which of them still hold. The listings in this article were produced with CPython 3.12; the reason why that detail matters is explained in the section devoted to version changes.
From Source Code to Code Objects
CPython does not execute source text directly. Each function is compiled once, when its definition runs, into a code object that contains the bytecode together with the constants, names and local variables that the bytecode refers to. That object is reachable through the attribute __code__, as the following example shows.
def seconds_per_day():
return 24 * 60 * 60
code = seconds_per_day.__code__
print(type(code).__name__) # Output: code
print(86400 in code.co_consts) # Output: True
print(code.co_varnames) # Output: ()
The second line reveals a first optimization: the multiplication 24 * 60 * 60 never runs, because the compiler computes it in advance and stores the result 86400 among the constants of the function, a technique known as constant folding. The bytecode is then executed by the interpreter's evaluation loop, which is often called the Python virtual machine. It must be noted, however, that this whole mechanism belongs to CPython; other implementations, such as PyPy, compile and execute code in their own way.
Reading Bytecode with dis
The present section introduces the module dis, whose name abbreviates "disassembler". In real-time strategy games, certain units remain invisible until a detector unit is brought nearby, and only then can the player see what was already on the field. The module dis plays that role for the interpreter: it does not change the code, but it reveals the instructions that were already there. The following function is disassembled with it.
import dis
def simple_add():
a = 10
b = 20
c = a + b
dis.dis(simple_add)
On CPython 3.12, the call prints the following listing.
3 0 RESUME 0
4 2 LOAD_CONST 1 (10)
4 STORE_FAST 0 (a)
5 6 LOAD_CONST 2 (20)
8 STORE_FAST 1 (b)
6 10 LOAD_FAST 0 (a)
12 LOAD_FAST 1 (b)
14 BINARY_OP 0 (+)
18 STORE_FAST 2 (c)
20 RETURN_CONST 0 (None)
Each line contains the source line number, the offset of the instruction, its name and its argument. The interpreter works with a stack, and the instructions can be read in that light, as the following list describes:
RESUMEmarks the start of the function and is used internally by the interpreter.LOAD_CONSTpushes a constant onto the stack, andSTORE_FASTpops it into a local variable.LOAD_FASTpushes the value of a local variable.BINARY_OPpops two values, applies the operator indicated by its argument and pushes the result; for objects of user-defined classes, it is the instruction that ends up calling the special method__add__described in the article devoted to the data model.RETURN_CONSTreturns the constantNone, which every function returns when it has noreturnstatement.
The detector, however, has a limit that the analogy should not hide: dis shows the bytecode before the interpreter specializes it at runtime, so some of what the interpreter actually executes remains invisible in the default listing.
Why Tuples of Constants Are Cheaper than Lists
A frequent claim states that a tuple literal is created faster than the equivalent list. The bytecode explains the reason, and timeit confirms it.
import dis
import timeit
def make_list():
return [1, 2, 3]
def make_tuple():
return (1, 2, 3)
print([i.opname for i in dis.get_instructions(make_list)])
# Output: ['RESUME', 'BUILD_LIST', 'LOAD_CONST', 'LIST_EXTEND', 'RETURN_VALUE']
print([i.opname for i in dis.get_instructions(make_tuple)])
# Output: ['RESUME', 'RETURN_CONST']
for expression in ("[1, 2, 3]", "(1, 2, 3)"):
seconds = min(timeit.repeat(expression, number=1_000_000, repeat=5))
print(f"{expression}: {seconds * 1000:.0f} ns per evaluation")
# Output (CPython 3.12, varies by run): between 20 and 30 ns, and about 5 ns
The tuple (1, 2, 3) is immutable, so the compiler folds it into a single constant that the function returns as it is. The list, on the other hand, must be a new object on every call, because the caller may modify it; CPython therefore builds an empty list and extends it with the folded tuple of its elements. Since Python 3.9 this is the form that constant lists of three or more elements take, which differs from the sequence of three LOAD_CONST and one BUILD_LIST 3 that older versions produced. The measured difference, between four and six times on the machine used for this article, corresponds to the creation of a new list object, not merely to the number of instructions.
Local and Global Names: A Rule Worth Measuring
The bytecode also distinguishes local variables from global ones. A local variable is read with LOAD_FAST, which accesses an array by index, whereas a global name is read with LOAD_GLOBAL, which in principle requires a dictionary lookup. For years, this difference justified the advice of copying globals into local variables inside hot loops. The following example measures that advice on a modern interpreter.
import timeit
setup = """
K = 3
def use_global():
total = 0
for _ in range(10_000):
total += K
return total
def use_local():
k = 3
total = 0
for _ in range(10_000):
total += k
return total
"""
for name in ("use_global", "use_local"):
seconds = min(timeit.repeat(f"{name}()", setup=setup, number=500, repeat=7))
print(f"{name}: {seconds / 500 * 1e6:.0f} microseconds per call")
# Output (CPython 3.12, varies by machine): about 207 and 204 microseconds
The difference is close to one per cent, far smaller than the folk wisdom suggests. The reason lies in the specializing adaptive interpreter introduced by PEP 659 in Python 3.11: after a few executions, LOAD_GLOBAL is replaced internally by a specialized variant that caches the location of the name, so the dictionary lookup is no longer repeated on every access. Consequently, the mechanism that dis shows remains true, but its cost has changed, and only a measurement, such as those described in the article devoted to profiling, can decide whether a micro-optimization is worth applying.
Patch Notes: Bytecode Is Not a Stable Interface
The listings of this article would look different on another version of Python, and the documentation of dis states explicitly that bytecode may be added, removed or changed between versions. The listings that still circulate in many tutorials illustrate the point: they still show BINARY_ADD, an instruction that Python 3.11 replaced with BINARY_OP, and they lack RESUME, which appeared in the same version. In Python 3.14, the version current at the date of this article, the example listing of the official documentation already includes new instructions such as LOAD_FAST_BORROW. The version is also recorded in the compiled files that CPython caches on disk, as the following example shows.
import importlib.util
import sys
print(sys.implementation.cache_tag) # Output: cpython-312
print(importlib.util.cache_from_source("example.py"))
# Output: __pycache__/example.cpython-312.pyc (with the path separator of the system)
Each interpreter writes and reads its own .pyc files, distinguished by the cache tag introduced by PEP 3147 in Python 3.2, so bytecode compiled by one version is never executed by another. It follows that bytecode is an excellent tool for understanding and a poor foundation for code: a program that inspects opcode names, or a tool that relies on a specific listing, must be reviewed with each new version of Python.
When to Read Bytecode
Consequently, reading bytecode is most useful as an explanatory tool and least useful as a guide for daily optimization. The situations in which it helps, and those in which another tool is preferable, are summarized in the following table.
| Situation | Recommended approach |
|---|---|
| Understanding why two equivalent expressions behave differently | dis.dis() on both versions |
| Verifying that a constant expression is folded | dis.dis() or co_consts |
| Inspecting instructions from a program or a test | dis.get_instructions() |
| Deciding whether code is fast enough | timeit or a profiler, never the opcode count |
| Writing tools that depend on specific opcodes | Pinning the Python version and reviewing each release |
Conclusion
It is concluded that bytecode is the form in which CPython executes every function, and that the module dis turns it into a readable listing that explains constant folding, the cost of building lists and the distinction between local and global names. This secret weapon, however, explains mechanisms rather than measuring them: the advice about local variables shows that a rule derived from the bytecode can lose most of its value when the interpreter evolves. Its magic lies in replacing assumptions with evidence, provided that the evidence includes the version that produced it. The specializing adaptive interpreter, which rewrites instructions while a program runs, is the natural continuation of this topic and is developed in a future article of this series.