How does memory management and garbage collection work in Python?
· Category: Python Programming
Short answer
Python primarily uses reference counting to reclaim memory immediately when an object's references drop to zero. A cyclic garbage collector detects and breaks reference cycles involving only unreachable objects.
Steps
- Understand that
delremoves a reference, not necessarily the object. - Use
gc.get_objects()andgc.collect()for debugging. - Avoid reference cycles in long-running applications by using weak references.
import gc
import weakref
class Node:
def __init__(self, name):
self.name = name
self.parent = None
a = Node("a")
b = Node("b")
a.parent = b
b.parent = a
# Break cycle manually
del a, b
gc.collect()
# Weak reference
ref = weakref.ref(Node("temp"))
print(ref()) # None if collected
Tips
- Circular references between objects with
__del__methods can leak in older Python versions. weakrefis useful for caches and observer patterns where you do not want to prevent garbage collection.- Profile memory with
tracemallocto find leaks and high-allocation hotspots.
Common issues
- Global caches that never release objects are the most common source of memory leaks.
__del__is not guaranteed to run immediately or at all; use context managers for deterministic cleanup.- Generators and closures can inadvertently hold references to large objects.