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

  1. Understand that del removes a reference, not necessarily the object.
  2. Use gc.get_objects() and gc.collect() for debugging.
  3. 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.
  • weakref is useful for caches and observer patterns where you do not want to prevent garbage collection.
  • Profile memory with tracemalloc to 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.