Python › Memory Management & Garbage Collection

How does the gc module let you inspect and debug memory leaks caused by uncollectable objects?

Intermediate

Answer

gc.collect() returns the number of unreachable objects it found and collected; gc.garbage lists objects the collector found uncollectable (in older Python versions, mainly ones with __del__ methods in cycles). gc.set_debug(gc.DEBUG_LEAK) and get_objects()/get_referrers() help trace what's holding references to unexpectedly long-lived objects during memory leak investigation.
import gc

gc.set_debug(gc.DEBUG_STATS)
unreachable = gc.collect()
print(f'Collected {unreachable} unreachable objects')
print(gc.garbage)  # objects that couldn't be collected
Real-world example A long-running service investigates a slow memory leak by periodically calling gc.collect() and logging gc.garbage to identify which custom classes with __del__ methods are stuck in uncollectable cycles.

Common follow-ups: How do you use gc.get_referrers() to trace what's keeping an object alive?;What tools like objgraph help visualize reference graphs?