Sub topic 13
Common memory leak patterns and fixes
This chapter assumes you know how reference counting and the cyclic collector work, and that you can run a script with tracemalloc. A Python leak is almost never memory the interpreter lost. It is an object you still reference, so the collector is right not to free it.
What a leak looks like in Python
Memory grows over time and does not level off. Some live reference, often a global container, keeps every new object reachable. The fix is to find that reference and remove it, bound it, or make it weak.
Pattern 1: unbounded caches and globals
A module-level dictionary or list that only grows is the most common leak. Every entry stays reachable for the life of the program.
import tracemalloc
leaky = []
def handle_request(n):
leaky.append("payload" * 1000)
tracemalloc.start()
before = tracemalloc.take_snapshot()
for n in range(1000):
handle_request(n)
after = tracemalloc.take_snapshot()
for stat in after.compare_to(before, "lineno")[:3]:
print(stat)The top line of the output points at the append call, with a size difference of several megabytes. Comparing two snapshots shows growth. A single snapshot only shows what is large.
To fix a cache, give it a limit.
from functools import lru_cache
@lru_cache(maxsize=1024)
def load(key):
return str(key) * 100
for i in range(5000):
load(i)
print(load.cache_info().currsize) # 1024lru_cache with no maxsize argument defaults to 128. maxsize=None is unbounded and brings the leak back.
Pattern 2: caches that should not own their values
Sometimes a registry should only describe objects that exist for other reasons. A WeakValueDictionary holds its values weakly, so an entry disappears when the last strong reference goes.
import weakref
class Session:
def __init__(self, user):
self.user = user
sessions = weakref.WeakValueDictionary()
s = Session("ana")
sessions["ana"] = s
print(len(sessions)) # 1
del s
print(len(sessions)) # 0 in CPythonWeakSet and WeakKeyDictionary work the same way. This also fits listener lists: a subject that stores observers in a WeakSet does not keep them alive.
Pattern 3: hidden references
These leaks are harder to spot because no container is obviously growing.
| Source of the reference | Why it keeps objects alive | Fix |
|---|---|---|
| Stored exception object | Its traceback references every frame and local variable on the way up | Store `str(e)` or the fields you need |
| Closure or bound method as a callback | The function holds `self` or captured variables | Unregister callbacks, or use `weakref.WeakMethod` |
| Default mutable argument | The default is created once and shared by all calls | Use `None` and create the list inside the function |
| Long-lived list of results | The list holds the full objects when you need a few fields | Keep only the fields, or use a generator |
| Reference cycles with large objects | They wait for the cyclic collector, which can be late | Break the cycle explicitly or use a weak reference |
Working method
- Reproduce the growth in a loop that you can repeat.
- Take a snapshot, run the suspect code many times, and take a second snapshot.
- Compare with
compare_to(before, "lineno")and read the top entries. - Trace the allocating line to whatever still references its objects.
- Apply the smallest fix (remove, bound, or weaken the reference) and measure again.
Do not call gc.collect() as a fix. If memory stays high after a collection, the objects are still reachable and need a code change.
Exercise
A web service keeps seen = {} at module level and adds seen[request_id] = response on every request. Memory grows without limit. Give two ways to fix it, and say when each fits.
Show answer
Bound the cache by replacing the dictionary with an lru_cache-decorated function, or by evicting old entries yourself. This fits when you need recent responses for repeat requests. Alternatively, use a WeakValueDictionary, which fits only if something else already holds the responses and you want lookups while they live. If you never read seen again, remove it.