How CPython Works: Bytecode, Objects, the Cycle Collector and the GIL
This lesson is optional depth. Nothing later in the track needs it, and you can skip it and come back when one of those surprises happens. It sits after the capstone, for readers who want to know how CPython works. "CPython" is the standard interpreter, the one you get from python.org and the one this site runs, written in C.
After this lesson, you will be able to:
- Show the bytecode CPython compiles for a small function with dis and say what each instruction does to the stack
- Name the two fields every Python object starts with and what they are for
- Create a reference cycle, show that del does not free it, and free it with gc.collect() or a weak reference
- Describe what the GIL protects and when a thread gives it up
- Say what the free-threaded build is, and tell which build you are running apart from whether the GIL is on right now
- Explain why a process can stay large after you free a big structure, using the allocator
- Explain why NumPy code can use several threads at once while pure Python loops cannot
Before you start
is versus ==, the small-integer cache, string interning and the basics of reference counts are in the lesson on Python's memory model. What the GIL is, and when to pick threads, processes or asyncio, is in the lesson on async and concurrency. This lesson adds how CPython does each of those things.#From Source to Bytecode
Python is not run line by line from your text. When you start a script, CPython first compiles it, then a virtual machine runs the result. The compile step has three stages you can look at yourself.
- The parser reads your text and builds an abstract syntax tree (AST), a tree that records the structure of the code.
- The compiler walks the tree and emits bytecode, a list of small instructions.
- The virtual machine, a program that acts like a small computer for bytecode, runs those instructions one at a time.
compile gives you the same object the interpreter builds, and ast shows the tree before it.import ast
tree = ast.parse("x = 1 + 2")
print(ast.dump(tree.body[0], indent=2))
code = compile(tree, "<demo>", "exec")
print(code.co_consts, code.co_names)
exec(code)
print(x)Output:
Assign(
targets=[
Name(id='x', ctx=Store())],
value=BinOp(
left=Constant(value=1),
op=Add(),
right=Constant(value=2)))
(3, None) ('x',)
3
x". The code object holds the folded constant 3 and None (3.14 stores small integers differently, so its constants differ) and the name x. The compiler already added 1 + 2 and stored 3, so the addition never happens at run time. This is called constant folding. The compiler does the work once so the virtual machine does not repeat it..pyc file under __pycache__, so the next import skips compiling. A .pyc file is tied to a Python version, which is why the file name contains cpython-312 or similar.#Reading Bytecode with dis
dis module prints the bytecode of a function. Start with the smallest function there is.import dis
def add(a, b):
return a + b
dis.dis(add)Output on Python 3.12:
3 0 RESUME 0
4 2 LOAD_FAST 0 (a)
4 LOAD_FAST 1 (b)
6 BINARY_OP 0 (+)
10 RETURN_VALUE
RESUME is bookkeeping at the start of every function. The two LOAD_FAST instructions fetch the local variables a and b. BINARY_OP adds them. RETURN_VALUE hands back the result.#The stack machine in one example
x * w + b, shows the whole idea.import dis
def score(x, w, b):
z = x * w + b
return z
for ins in dis.get_instructions(score):
print(ins.offset, ins.opname, ins.argrepr)Output on Python 3.12:
0 RESUME
2 LOAD_FAST x
4 LOAD_FAST w
6 BINARY_OP *
10 LOAD_FAST b
12 BINARY_OP +
16 STORE_FAST z
18 LOAD_FAST z
20 RETURN_VALUE
dis.get_instructions yields the same instructions as data, which is handy when you want to count or search them. The offsets skip numbers because some instructions are followed by hidden cache slots that the interpreter uses to run faster. On 3.13 the two loads at the start become one LOAD_FAST_LOAD_FAST, so the listing has eight instructions there and nine on 3.12. The stepper below runs score(2, 3, 1) through exactly the nine 3.12 instructions, with the stack drawn after each one. The only simplification is that RESUME is shown doing nothing.score(2, 3, 1): the real 3.12 instructions and the stack after each
Step through the compiled bytecode instruction by instruction and watch the evaluation stack grow and shrink.
Python source and its 9 bytecode instructions, with the evaluation stack after the selected instruction. Currently at instruction 1, RESUME 0, leaving 0 items on the stack. Each instruction pushes or pops stack values, and the instruction data is supplied by the lesson.
def score(x, w, b):
z = x * w + b
return z
score(2, 3, 1)RESUME 0: Start-of-function bookkeeping. It does not touch the stack.
How many BINARY_OP instructions does the bytecode for z = x * w + b contain?
What does this teach you in practice? A line of Python is not one step. It is a short program, and the interpreter pays for every instruction, which is one reason a loop of simple arithmetic in pure Python is slow next to a single NumPy call that does the loop in C.
#The listing changes while the program runs
dis hides this by default. Pass adaptive=True to see the instructions that are actually executing.import dis
def add(a, b):
return a + b
for _ in range(1000):
add(1, 2)
dis.dis(add, adaptive=True)Output on Python 3.12:
3 0 RESUME 0
4 2 LOAD_FAST__LOAD_FAST 0 (a)
4 LOAD_FAST 1 (b)
6 BINARY_OP_ADD_INT 0 (+)
10 RETURN_VALUE
BINARY_OP has become BINARY_OP_ADD_INT, because add has only ever seen two integers, and the two loads have been fused into one LOAD_FAST__LOAD_FAST. The specialised instruction checks that both values are still integers and then adds them without the general lookup. If the types change, the interpreter notices and specialises again.import dis
def add(a, b):
return a + b
def operator_name():
names = [i.opname for i in dis.get_instructions(add, adaptive=True)]
return [n for n in names if n.startswith("BINARY_OP")][0]
print("before any call:", operator_name())
for _ in range(1000):
add(1, 2)
print("after integers:", operator_name())
for _ in range(1000):
add("a", "b")
print("after strings: ", operator_name())Output:
before any call: BINARY_OP
after integers: BINARY_OP_ADD_INT
after strings: BINARY_OP_ADD_UNICODE
RESUME_CHECK and LOAD_FAST_LOAD_FAST here), so read them as an explanation, not as an interface. Bytecode is a good way to see what a line does and a poor way to predict speed. To compare two versions of code, measure them with timeit.#What a Python Object Is
1 to a function, is an object, and in the default build every object begins with the same two fields. The first is a reference count: how many references point at the object now. The second is a reference to its type, which is how Python knows what +, len or .append should do for it.PyObject. (The free-threaded build, described later, keeps its counts differently and has a larger header.)sys.getsizeof reports an object's own size in bytes. It does not follow references to other objects, so for a container it counts the pointers but not what they point at.import struct
import sys
pointer = struct.calcsize("P")
print("a float object is bigger than a raw 8-byte double:", sys.getsizeof(1.0) > 8)
print("an int object is bigger than the 4 bytes a C int needs:", sys.getsizeof(1) > 4)
print("a bigger int takes more room:", sys.getsizeof(2**100) > sys.getsizeof(1))
print("a str costs one byte per ASCII character:", sys.getsizeof("hello") - sys.getsizeof("") == 5)
print("1000 more list items cost 1000 pointers:", sys.getsizeof([0] * 1000) - sys.getsizeof([]) == 1000 * pointer)Output:
a float object is bigger than a raw 8-byte double: True
an int object is bigger than the 4 bytes a C int needs: True
a bigger int takes more room: True
a str costs one byte per ASCII character: True
1000 more list items cost 1000 pointers: True
sys.getsizeof gives 28 for 1, 24 for 1.0, 46 for "hello", 56 for [], 88 for [1, 2, 3] and 64 for (1, 2, 3). The browser runs 32-bit WebAssembly, where a pointer is 4 bytes and the same six values give 16, 16, 26, 28, 44 and 32.double takes 8 on the desktop, and 16 in the browser. A list of three items costs the list header plus room for its pointers, and the three integers are counted separately. Now scale that to a column of a million feature values.import sys
from array import array
floats = [float(i) for i in range(1_000_000)]
container = sys.getsizeof(floats)
objects = sum(sys.getsizeof(v) for v in floats)
raw = array("d", floats)
raw_bytes = len(raw) * raw.itemsize
print("raw doubles take 8 bytes each:", raw_bytes == 8_000_000)
print("float objects take more room than the list pointers:", objects > container)
print("list plus floats is more than twice the raw size:", container + objects > 2 * raw_bytes)Output:
raw doubles take 8 bytes each: True
float objects take more room than the list pointers: True
list plus floats is more than twice the raw size: True
On a 64-bit desktop the list pointers take 8,448,728 bytes, the float objects 24,000,000 and the list in total 32,448,728, against 8,000,000 for the raw doubles: about four times as much.
array module packs the numbers side by side. This is the reason NumPy stores data in one block of memory, side by side, and wraps the whole block in a single Python object. The cost of the object model is paid once per array, not once per number.#The Cyclic Garbage Collector
Reference counting frees an object the moment its count reaches zero, and that covers almost every object in a program. It fails in one case. If two objects point at each other, each keeps the other's count above zero, even when nothing else in the program can reach either of them.
None if it was freed.import gc
import weakref
class Node:
def __init__(self, name):
self.name = name
self.other = None
gc.collect()
gc.disable()
a = Node("a")
b = Node("b")
a.other = b
b.other = a
probe = weakref.ref(a)
del a, b
print("alive after del:", probe() is not None)
found = gc.collect()
print("alive after collect:", probe() is not None)
print("collector found something:", found > 0)
gc.enable()Output:
alive after del: True
alive after collect: False
collector found something: True
del a, b the program has no names for the two nodes, yet they are still in memory because each holds the other. gc.collect() runs the cyclic garbage collector. It looks at objects that can hold references, works out which of them are reachable (you can get to them by following references from the program's variables), and frees the groups that are not. The cell disables the automatic collector first so the demonstration does not depend on when it happens to run, and enables it again at the end.gc.collect() and frees both.gc.collect() yourself, because the collector runs on its own. It is organised in generations: new objects are examined often and objects that survive many examinations are examined rarely, on the observation that most objects die young. Three numbers control when it runs, and they change between releases.import gc
print(gc.get_threshold())(700, 10, 10). On 3.13 the same call returns (2000, 10, 10), and on 3.14 it returns (2000, 10, 0). The first number is roughly how many new container objects trigger a young-generation pass. Do not tune these without a measurement that shows a problem. What stays true on every version is the idea: counting frees most objects at once, and the collector is the safety net for cycles.A script builds a large graph of nodes that point at each other, deletes every name that refers to it, and memory use does not drop right away. What is the most likely explanation?
#Where Memory Comes From
CPython does not ask the operating system for memory every time it creates an object. Most objects are small, so the default desktop build uses its own allocator, called pymalloc, for anything up to 512 bytes. An allocator is the part of a program that hands out memory and takes it back. The allocator asks the operating system for large chunks called arenas, cuts each into smaller sections, and hands out fixed-size slots from them. Freed slots go back to the allocator, ready for the next object of that size, which is why creating and discarding small objects is cheap.
top can stay high even though Python reports the memory as released. Use tracemalloc for what Python holds and the process size for what the operating system sees. The first cell measures the Python side.import tracemalloc
tracemalloc.start()
items = [(i, i + 1) for i in range(100_000)]
peak = tracemalloc.get_traced_memory()[0]
kept = items[::10]
del items
left = tracemalloc.get_traced_memory()[0]
print("Python still holds", round(left / peak, 1), "of what it held at the peak")
tracemalloc.stop()Output:
Python still holds 0.1 of what it held at the peak
ps, so it is read-only here: it needs a desktop terminal, and the browser build has no pymalloc at all.import os
import subprocess
# Resident memory of this process, as the operating system reports it.
def process_mb():
out = subprocess.run(["ps", "-o", "rss=", "-p", str(os.getpid())],
capture_output=True, text=True)
return int(out.stdout) / 1024
def grown_then_deleted(keep_every):
start = process_mb()
items = [(i, i + 1) for i in range(1_000_000)]
peak = process_mb() - start
kept = items[::keep_every]
del items
left = process_mb() - start
return round(left / peak, 2)
print("delete everything: ", grown_then_deleted(10_000_000))
print("keep one tuple in ten: ", grown_then_deleted(10))0.09 and 1.0 (3.13 gave the same). When every tuple was deleted, the process fell back to about nine percent of its peak growth. When one tuple in ten was kept, the process stayed at the full peak: the survivors were spread through every arena, so no arena was empty enough to return.The exact numbers depend on the operating system, but the pattern is the point. A process that has held a big structure may stay big after you free most of it, and the usual remedies are to free all of it, to keep results in a compact form such as an array, or to do the heavy step in a short-lived worker process.
sys._debugmallocstats(). It writes a long table to standard error, so it is a command-line tool rather than something to run in the browser. The first line it prints is Small block threshold = 512, in 32 size classes.tracemalloc, which tracks how much memory your Python code has allocated. Here it compares two ways to store 10,000 rows.import tracemalloc
def traced_kib(make_row):
tracemalloc.start()
rows = [make_row(i) for i in range(10_000)]
current, _ = tracemalloc.get_traced_memory()
tracemalloc.stop()
return current / 1024
dict_kib = traced_kib(lambda i: {"x": i, "y": i * 2})
tuple_kib = traced_kib(lambda i: (i, i * 2))
print("a dict per row costs more than a tuple per row:", dict_kib > tuple_kib)
print("the dict version costs over 1.5 times as much:", dict_kib > 1.5 * tuple_kib)Output:
a dict per row costs more than a tuple per row: True
the dict version costs over 1.5 times as much: True
tracemalloc reported 2492 KiB for 10,000 rows on my 64-bit desktop with Python 3.13, about 255 bytes per row. The browser reports about half that, for the same reason as the sizes above.tracemalloc.take_snapshot() and call compare_to on the later one. That is the standard way to locate a leak. A model that keeps growing between batches is usually holding references it should have dropped, and the snapshot comparison names the line that made them.#The GIL: What It Protects
The global interpreter lock (GIL) is a lock, which means only one thread can hold it at a time. (A thread is one path of execution inside a program.) A thread must hold the GIL to run Python bytecode. Why does CPython need it? Because of reference counts. Every time a reference is created or dropped, a count changes. If two threads changed the same count at once, one update could overwrite the other, and the count would end up wrong. A wrong count means an object freed while still in use, which crashes the interpreter, or never freed, which leaks.
One lock around the whole interpreter is the simplest fix, and it also protects every other internal structure. The price is that two threads cannot run Python bytecode at the same moment, even on a machine with many cores.
sys.getswitchinterval() reports it.import sys
print(sys.getswitchinterval())0.005, which is five milliseconds, the documented default. And a thread that blocks on something outside Python, such as reading a file, waiting for a network reply or sleeping, releases the lock while it waits. That is why threads help with I/O and not with pure Python arithmetic: the waiting threads are not using the lock, and the computing thread never finishes a wait.Here is a measurement of that second claim. Threads cannot start in the browser, so this cell is read-only. It ran on a ten-core laptop with the packages from this track installed.
import threading
import time
def count():
i = 0
while i < 3_000_000:
i += 1
def seconds(fn, n=4):
start = time.perf_counter()
for _ in range(n):
fn()
one_after_another = time.perf_counter() - start
threads = [threading.Thread(target=fn) for _ in range(n)]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
return one_after_another, time.perf_counter() - start
print(seconds(count))(0.21, 0.20): four threads took the same time as four calls in a row. The next section runs the same experiment on code that uses NumPy.#Why NumPy Escapes the GIL
np.sin.import threading
import time
import numpy as np
x = np.random.rand(200_000)
def work():
for _ in range(300):
np.sin(x)
def seconds(fn, n=4):
start = time.perf_counter()
for _ in range(n):
fn()
one_after_another = time.perf_counter() - start
threads = [threading.Thread(target=fn) for _ in range(n)]
start = time.perf_counter()
for t in threads:
t.start()
for t in threads:
t.join()
return one_after_another, time.perf_counter() - start
print(seconds(work))(0.77, 0.21): four threads took roughly a quarter of the time of four calls in a row. The threads really did run on separate cores at the same moment, because inside np.sin none of them held the lock. The speed-up depends on the operation. Work that is limited by how fast memory can be read, such as a plain np.sqrt over a very large array, gained much less when I tried it.This is the practical rule. Threads help when most of the time is spent waiting, or inside C code that releases the lock. They do not help for loops written in Python. For those, the track's earlier lesson on concurrency covers processes.
#The Free-Threaded Build
python3.13t. In the default build, the one you get without asking for anything special, the GIL is still there, and that stays true on 3.14. In 3.13 the free-threaded build is marked experimental. In 3.14 it is officially supported, and it is still optional.Removing the lock means the interpreter must keep reference counts and its internal structures safe with other techniques, which PEP 703 describes, and C extensions have to be rebuilt to work with it. Code that runs on one thread may be somewhat slower there. Its payoff is that several threads can run Python bytecode at the same time.
PYTHON_GIL=1 or by importing a C extension that is not ready for it. So sys._is_gil_enabled(), which exists from 3.13, answers the second question, and the build is recorded in the configuration that sysconfig reads. Guard the call, because older versions do not have it.import sys
import sysconfig
print("free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED") == 1)
check = getattr(sys, "_is_gil_enabled", None)
print("GIL on right now:", True if check is None else check())Output on a default CPython 3.12, 3.13 or 3.14, including the site's runner (Python 3.12, where the function does not exist and the GIL is always on):
free-threaded build: False
GIL on right now: True
True, and the second prints False unless something has turned the GIL back on.#Common Mistakes
Four mistakes come up when people start working with these tools.
#Expecting del to free a cycle
import gc
import weakref
class Node:
def __init__(self):
self.other = None
gc.disable()
a, b = Node(), Node()
a.other, b.other = b, a
probe = weakref.ref(a)
del a, b
print(probe() is None)
gc.enable()Output:
False
del removes a name and lowers a count by one. In a cycle that count never reaches zero. Break the cycle before you delete, or make the back-link weak so it never adds to the count.import gc
import weakref
class Node:
def __init__(self):
self.other = None
gc.disable()
a, b = Node(), Node()
a.other = b
b.other = weakref.ref(a)
probe = weakref.ref(a)
del a, b
print(probe() is None)
gc.enable()Output:
True
a points at b, and b holds only a weak reference to a. No cycle of counts exists, so deleting the names frees both at once.#Treating getsizeof as the full size
import sys
small = [0]
big = [list(range(1000))]
print("same size reported:", sys.getsizeof(small) == sys.getsizeof(big))
print("the inner list is larger than its container:", sys.getsizeof(big[0]) > sys.getsizeof(big))Output:
same size reported: True
the inner list is larger than its container: True
sys.getsizeof is shallow. Use tracemalloc to measure what a structure really costs.#Calling a 3.13 function on an older Python
>>> import sys
>>> sys._is_gil_enabled()
Traceback (most recent call last):
...
AttributeError: module 'sys' has no attribute '_is_gil_enabled'getattr, as in the previous section, and report the version with sys.version_info when you ask for help.#Reaching for gc.disable() as a speed-up
gc.enable() afterwards.#Try It
gc.collect().Each child keeps a reference to its parent, and the parent keeps a list of children, so a deleted tree stays in memory. Make the child's link to its parent a weak reference so the tree is freed as soon as the last name is deleted.
freed: True
dis.get_instructions, time each with timeit, and print the two numbers side by side.Tests: assert count > 0 and seconds > 0
dis.get_instructions(fn) yields one object per instruction, so len(list(...)) counts them. The times change from run to run and machine to machine, so compare the two functions with each other, not with a number from this page. Notice that with_sum has fewer instructions than with_loop, yet that count did not tell you which one runs faster, because get_instructions counts only the outer function: the generator expression is a separate code object with its own instructions.#Going Further
cProfile and compare two versions with timeit, before you read any bytecode. When pure-Python loops are the bottleneck and cannot be rewritten as whole-array operations, other implementations and compilers exist: PyPy compiles hot loops while the program runs, and Cython and Numba compile typed code. Each gives up some compatibility with the C extension ecosystem, so measure on your own workload before switching. The CPython source is public, and Python/bytecodes.c defines what each instruction does.Key takeaways
- CPython compiles source to bytecode and a stack-based virtual machine runs it; dis shows the instructions, their names change between Python versions, and from 3.11 hot instructions are rewritten after warm-up (dis.dis(f, adaptive=True) shows it).
- Every object starts with a reference count and a reference to its type, which is why a Python float is 24 bytes on a 64-bit desktop build (16 in the browser) and why NumPy keeps raw numbers in one block.
- Reference counting frees almost everything at once, and the cyclic collector exists for groups of objects that point at each other. Freed memory returns to Python's allocator, not always to the operating system.
- The GIL stops two threads running bytecode at once because reference counts are not safe otherwise; threads release it while they wait or inside C code such as NumPy.
- The free-threaded build is optional. The default 3.13 and 3.14 builds keep the GIL. sysconfig.get_config_var('Py_GIL_DISABLED') says which build you have; sys._is_gil_enabled() says whether the GIL is on right now.
In CPython's bytecode for `z = x * w + b`, in what order do the values move on the stack?