How does Python memory management work?
CPython combines:
- Reference counting for immediate reclamation. Every object tracks how many references point to it; when the count hits zero it is freed.
- A cyclic garbage collector (generational, gc module) to collect reference cycles that counting cannot handle.
- Private heaps and freelists per object type for fast allocation, plus pymalloc for small objects.
Interview extras: __del__ finalisers, weak references (weakref) to avoid keeping objects alive, and context managers to release resources deterministically with __enter__/__exit__ rather than relying on the GC.