Memory & the GIL
Reference counting and the cyclic garbage collector, weak references, memory profiling, the Global Interpreter Lock — why it exists, what it does and doesn't protect, its impact on threads — and the free-threaded (no-GIL) Python builds.
Two facts shape Python's runtime behaviour: memory is managed mainly by reference counting, and, in standard builds, the Global Interpreter Lock (GIL) lets only one thread execute Python bytecode at a time. They're deeply connected.
Reference counting
Every object carries a count of references to it (CPython internals). The count goes up when a reference is created (assignment, putting it in a container, passing it to a function) and down when one disappears (a name rebound or deleted, a container cleared, a function returns).
import sys
a = []
sys.getrefcount(a) # 2 (a, plus the temporary argument reference)
b = a
sys.getrefcount(a) # 3
del b
sys.getrefcount(a) # 2When the count reaches zero, the object is freed immediately, and its __del__ (if any) runs. Benefits: predictable, prompt release of memory and resources (files closed when the last reference goes away in CPython). Costs: every reference operation touches memory (bad for caches and multi-threading), and cycles are never freed by counting alone.
The cyclic garbage collector
class Node:
def __init__(self):
self.other = None
a, b = Node(), Node()
a.other, b.other = b, a # a ↔ b
del a, b # each still has refcount 1 from the other: leaked without GCThe gc module runs a generational cycle detector over container objects (lists, dicts, class instances — not ints or strings):
- Objects start in generation 0. Survivors of a collection are promoted to gen 1, then gen 2.
- A collection is triggered when allocations minus deallocations exceed a threshold (
gc.get_threshold()); young generations are collected far more often. - To find garbage cycles, the GC copies each object's refcount, subtracts references coming from inside the examined set, and anything left with zero external references — and not reachable from something with external references — is unreachable garbage.
(Python 3.14 moved to an incremental collector with fewer generations to cut pause times; the principle is the same.)
import gc
gc.collect() # force a full collection; returns the number of unreachable objects found
gc.disable() # some latency-sensitive services disable it and call collect() at safe points
gc.freeze() # move all current objects to a permanent generation (useful before fork())Weak references
A weak reference refers to an object without increasing its refcount, so it doesn't keep the object alive. Useful for caches and back-references that shouldn't cause leaks or cycles.
import weakref
class Image: ...
cache = weakref.WeakValueDictionary()
img = Image()
cache["logo"] = img
del img # last strong reference gone → the cache entry disappears
"logo" in cache # False
parent_ref = weakref.ref(parent) # call parent_ref() to get the object or NoneFinding memory problems
| Tool | Use |
|---|---|
sys.getsizeof(obj) | Shallow size of one object |
tracemalloc (stdlib) | Which lines allocated memory; compare snapshots to find growth |
memray, scalene | Detailed allocation profiling, including native code |
objgraph, gc.get_referrers | Who is holding a reference to a leaked object |
import tracemalloc
tracemalloc.start()
run_workload()
for stat in tracemalloc.take_snapshot().statistics("lineno")[:5]:
print(stat)Common leaks: unbounded caches/global lists, functools.cache on methods (keeps self alive), lingering references in exception tracebacks, and C extensions.
The Global Interpreter Lock
The GIL is a mutex in CPython that a thread must hold to execute Python bytecode or touch Python objects.
Why it exists
- Reference counts are modified constantly; without a lock, two threads incrementing the same count could corrupt it, leading to leaks or use-after-free crashes. Making every refcount update atomic (or locking each object) was much slower for single-threaded code.
- It made writing C extensions easy: they can assume they own the interpreter while holding the GIL.
How it behaves
- A running thread holds the GIL; others wait.
- The holder releases it periodically (every 5 ms switch interval,
sys.getswitchinterval()) when another thread is waiting, and always releases it around blocking I/O (socket reads, file reads,time.sleep). - C extensions (NumPy, hashlib, zlib, many ML libraries) release it during long computations.
Two CPU-bound threads take turns: on a multi-core machine, total throughput is no better than one thread (often slightly worse, due to switching).
Consequences
| Workload | Threads help? | Better option |
|---|---|---|
| I/O-bound (HTTP calls, DB queries, files) | Yes — the GIL is released while waiting | threading, ThreadPoolExecutor, or asyncio |
| CPU-bound pure Python | No | multiprocessing / ProcessPoolExecutor (one GIL per process) |
| CPU-bound in C extensions (NumPy, compression) | Often yes — they release the GIL | Threads are fine |
Free-threaded Python (no GIL)
PEP 703 made the GIL optional. Python 3.13 shipped an experimental free-threaded build (python3.13t); in 3.14 it became officially supported (though still a separate build, not the default). Making it work required:
- Biased reference counting: the owning thread updates a non-atomic local count; other threads use an atomic shared count.
- Immortal objects:
None,True, small ints and interned strings never change refcount. - Per-object locks for built-in containers (list, dict) so concurrent operations don't corrupt them.
- mimalloc, a thread-safe allocator; deferred reference counting for some objects.
Trade-offs: single-threaded code is somewhat slower (initially ~40% in 3.13, much less in 3.14), and C extensions must declare free-threading support or the GIL is re-enabled. CPU-bound threads finally scale across cores.
Subinterpreters
Another path to parallelism: multiple interpreters in one process, each with its own GIL (PEP 684, 3.12), exposed via concurrent.interpreters (3.14). Isolation like processes, lower overhead.
- Reference counting frees objects immediately when their count hits zero.
- A generational cycle collector frees unreachable reference cycles.
- Weak references refer without keeping objects alive; tracemalloc finds leaks.
- The GIL lets one thread run bytecode at a time; it's released during I/O and by many C extensions.
- Threads help I/O-bound work; use processes for CPU-bound pure Python.
- The GIL doesn't make your code thread-safe; free-threaded builds (3.13+) remove it at some cost.
QWhat is the GIL and why does Python have it?medium
The Global Interpreter Lock is a mutex in CPython that allows only one thread at a time to execute Python bytecode. It exists because CPython's memory management relies on non-atomic reference counting and its internals weren't designed for concurrent access; a single lock kept single-threaded code fast and C extensions simple. The consequence is that CPU-bound Python threads don't run in parallel, though I/O-bound threads benefit because the GIL is released while waiting.
QHow does Python manage memory?medium
Primarily through reference counting: each object tracks how many references point to it and is freed as soon as the count reaches zero. Because cycles can never reach zero, a generational cyclic garbage collector periodically detects and frees unreachable cycles. Small objects are allocated from pools by pymalloc to reduce fragmentation and allocation cost.