Python Garbage Collection (gc)
Python uses automatic memory management. The primary mechanism is reference counting, but it also has a garbage collector (GC) to detect and collect reference cycles. The gc module provides an interface to this cyclic garbage collector.
Reference Counting vs Garbage Collection
- Reference Counting: Python's main memory management technique. Objects are deallocated immediately when their reference count drops to zero.
- Garbage Collection: A background process that searches for and cleans up objects that reference each other (cyclic references) but are no longer reachable from the application.
Importing the Module
import gc
Controlling the Garbage Collector
You can enable or disable the cyclic garbage collector.
import gc
# Check if GC is enabled
print(gc.isenabled()) # Output: True
# Disable GC
gc.disable()
# Enable GC
gc.enable()
Forcing Collection
You can trigger a manual garbage collection process using gc.collect(). This is useful in memory-constrained environments or for debugging.
import gc
# Run a full collection
n = gc.collect()
print(f"Number of unreachable objects collected: {n}")
Debugging Memory Leaks
The gc module allows you to inspect objects that the collector found to be unreachable but could not be freed.
import gc
gc.set_debug(gc.DEBUG_LEAK)
# Force a collection to see what's leaking
gc.collect()