Sub topic 13
Common memory leak patterns and fixes
This chapter assumes you know how reference counting works, how the cyclic garbage collector finds unreachable cycles, how weak references behave, and how to take a tracemalloc snapshot. You should be comfortable with functions, classes, dictionaries, and decorators.
What a leak means in Python
CPython frees an object when nothing refers to it. Reference counting handles most objects, and the cyclic collector handles unreachable cycles. A true leak in the C sense, where memory is allocated and never reachable again, is rare in pure Python code.
What you usually see is a different problem: unintended retention. Your program keeps a strong reference to objects it no longer needs, so the collector is correct not to free them. The fix is almost always to remove or weaken the reference, not to call gc.collect().
The main patterns are:
- Containers that only grow, such as caches and registries.
- Callbacks and listeners that keep their targets alive.
- Exceptions whose tracebacks keep frames alive.
- Shared mutable state, such as default arguments and class attributes.
- Cycles that hold resources for longer than expected.
Pattern 1: unbounded caches and registries
A module-level dictionary used as a cache is the most common source of growth. Every new key adds an entry, and nothing removes old ones.
_cache = {}
def expensive(n):
if n not in _cache:
_cache[n] = [n] * 1000
return _cache[n]If n takes many different values over the life of the process, _cache grows without limit. The same applies to lists that collect log lines, results, or request records.
The fix is to bound the container. functools.lru_cache with a maxsize evicts the least recently used entries.
from functools import lru_cache
@lru_cache(maxsize=128)
def square(n):
return n * n
for i in range(1000):
square(i)
print(square.cache_info()) # CacheInfo(hits=0, misses=1000, maxsize=128, currsize=128)For data that is not a function result, use collections.deque(maxlen=N), which discards the oldest item when full.
from collections import deque
recent = deque(maxlen=3)
for i in range(10):
recent.append(i)
print(list(recent)) # [7, 8, 9]Another trap is using lru_cache on a method. The cache key includes self, so the cache holds a strong reference to every instance it has seen, and those instances stay alive until they are evicted. Cache a module-level function instead, or keep a per-instance cache.
Pattern 2: listeners and callbacks
An object that stores callbacks or listeners holds strong references to them. If subscribers register themselves and never unregister, they live as long as the publisher does.
class Publisher:
def __init__(self):
self.listeners = []
def subscribe(self, fn):
self.listeners.append(fn)A bound method such as widget.on_event holds a reference to widget. Subscribing it keeps widget alive, even after the rest of the program has dropped it.
There are two fixes. The first is explicit unsubscribe logic, which depends on every caller remembering to use it. The second is to store weak references, so the publisher never keeps a subscriber alive.
import weakref
class Publisher:
def __init__(self):
self._listeners = weakref.WeakSet()
def subscribe(self, listener):
self._listeners.add(listener)
def publish(self, msg):
for listener in list(self._listeners):
listener.notify(msg)
class Listener:
def notify(self, msg):
print("got", msg)
pub = Publisher()
lst = Listener()
pub.subscribe(lst)
pub.publish("hello") # got hello
del lst
print(len(pub._listeners)) # 0 in CPython: the listener was freedThe loop copies the set with list(...) first, because a listener could be freed while you iterate. If you store bound methods rather than objects, use weakref.WeakMethod. A plain weakref.ref(obj.method) dies immediately, because the bound method object is a temporary that nothing else references.
Pattern 3: tracebacks that keep frames alive
An exception object keeps a reference to its traceback through __traceback__. The traceback refers to each frame it passed through, and each frame refers to its local variables. If you store an exception, you also store every local variable from the functions that raised it.
import weakref
class Big:
pass
probes = []
def fail():
big = Big()
probes.append(weakref.ref(big))
raise ValueError("boom")
saved = None
try:
fail()
except ValueError as exc:
saved = exc
print(probes[0]() is not None) # True: saved -> traceback -> frame -> big
saved.__traceback__ = None
print(probes[0]()) # None: the frame and its locals were freedThe name exc is deleted automatically at the end of the except block, which prevents a cycle between the exception and the frame that holds it. Copying the exception into another variable, a list, a queue, or a Future bypasses that protection. This is common in code that collects errors from many tasks to report later. Store str(exc) or a formatted summary, or clear __traceback__ once you have logged it.
Pattern 4: shared mutable state
Two patterns create state that outlives its intended scope.
Mutable default arguments. The default value is created once, when the function is defined, and every call without that argument shares it.
def add(item, bucket=[]):
bucket.append(item)
return bucket
add(1)
print(add(2)) # [1, 2]: the same list is reused across callsThe fix is a None default:
def add(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketClass attributes used as instance state. A list defined in the class body is shared by every instance, and appending to it from any instance grows one object that lives as long as the class does. Create per-instance containers in __init__.
Pattern 5: cycles that delay release
The cyclic collector does free unreachable cycles, but only when it runs. Until then, every object in the cycle stays in memory, along with anything those objects reference, such as file handles, buffers, and database connections. A parent and child that point to each other, or an object that stores a bound method of itself, is enough to create one.
Two fixes help:
- Make the back-reference weak, for example a child's
parentattribute asweakref.ref(parent). - Release resources explicitly with
withblocks orclose()methods, so they do not depend on when the collector runs.
Finding the retainer with tracemalloc
For a growing process, take two snapshots and compare them. The comparison shows which source lines allocated memory that is still alive.
import tracemalloc
cache = {}
def handle(i):
cache[i] = f"payload-{i}-" * 100
tracemalloc.start()
before = tracemalloc.take_snapshot()
for i in range(10_000):
handle(i)
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:3]:
print(stat)The top entry points at the line inside handle that builds the string, with a size difference of several megabytes. That tells you where the retained data was created. You then search for what holds it, which here is the global cache.
Some practical points when you do this:
- Call
gc.collect()before taking each snapshot, so unreachable cycles do not appear as growth. - Take snapshots at the same point in a repeating cycle, such as after each request, so you compare like with like.
tracemallocshows where memory was allocated, not who references it. To find the holder, usegc.get_referrers(obj)on a suspect object, or look at what the growing lines have in common.- Tracing slows the program and adds memory overhead, so use it in a test or staging run rather than leaving it on in production.
Summary of patterns and fixes
| Pattern | Typical cause | Fix |
|---|---|---|
| Unbounded cache | Global dict, `cache`, `maxsize=None` | `lru_cache(maxsize=N)`, `deque(maxlen=N)` |
| Listener retention | Publisher stores strong references | `WeakSet`, `WeakMethod`, or unsubscribe |
| Stored exceptions | `__traceback__` holds frames and locals | Store a summary, or set `__traceback__ = None` |
| Shared state | Mutable default, class-level list | `None` default, create state in `__init__` |
| Delayed cycles | Parent and child references | Weak back-reference, `with` blocks |
Exercise
A service stores each failed request's exception in a global list errors so that an admin page can show them later. Memory grows steadily, and tracemalloc snapshots show large allocations at lines inside the request handlers. Explain why this happens and give two changes that stop it.
Show answer
Each stored exception keeps its __traceback__, which references every frame the exception passed through, and each frame keeps its local variables (such as request bodies and large buffers). The list also has no size limit. Changes: (1) store a small summary, such as repr(exc) or the formatted traceback text, instead of the exception object, or set exc.__traceback__ = None after logging; (2) bound the list with collections.deque(maxlen=N) so old entries are discarded.
Exercise
A class decorates its method with @lru_cache(maxsize=None). After the program creates and discards thousands of instances, none are freed. Why, and what is a fix?
Show answer
The cache key includes self, so the cache holds a strong reference to every instance that called the method. The instances can never be freed while the cache exists. Fix it by caching a module-level function that takes only the needed values, by giving each instance its own cache (for example a dict created in __init__), or by using a bounded maxsize so entries are evicted.