Investigate Retained Objects with Controlled Evidence
Core idea
A memory leak investigation separates unintended retention, allocation churn and allocator reuse. tracemalloc snapshots compare traced allocations at source locations; weak references can test whether a particular object remains live. Neither gives a complete native memory profile. Fix the ownership path rather than forcing frequent collection.
import gc, weakrefclass Item: passregistry=[]; x=Item(); r=weakref.ref(x)registry.append(x); del x; gc.collect()print(r() is not None)registry.clear(); gc.collect()print(r() is None)The registry is the intentional retention path; clearing it removes the root.
Expected output:
TrueTrueCompare traced snapshots
import tracemalloctracemalloc.start()try: before=tracemalloc.take_snapshot() data=[bytearray(4096) for _ in range(20)] after=tracemalloc.take_snapshot() print(any(s.size_diff>0 for s in after.compare_to(before,'lineno')))finally: tracemalloc.stop()The comparison identifies positive allocation differences; it is a clue, not proof of leakage.
Expected output:
TrueCommon mistake
gc.get_referrers can expose temporary inspection references and partially constructed objects. Use only on controlled debugging workloads, not as a production ownership oracle.
Practice
Repeat a bounded workload with and without a retained list; compare snapshot differences after releasing the list. Avoid claims about exact RSS.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory leak investigation
Check your understanding of memory leak investigation.
What is printed?
a=[]for i in range(3): a.append(bytearray(10))print(len(a))What is printed?
import tracemalloctracemalloc.start()s=tracemalloc.take_snapshot()print(type(s).__name__)tracemalloc.stop()What does a positive snapshot difference prove?
What is the appropriate first fix for an unbounded registry?