Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
CPython frees most objects immediately through reference counting when their count drops to zero, and a cyclic garbage collector periodically finds and frees groups of objects that reference each other.
Every object tracks how many references point to it; when the last reference disappears, the object is deallocated right away, which makes cleanup predictable. Reference counting cannot free cycles, such as two objects referring to each other, so the gc module runs a generational collector that inspects container objects and frees unreachable cycles. Small objects are allocated from pools managed by pymalloc, so freed memory is often reused by Python rather than returned to the operating system immediately. Memory problems in practice usually come from references kept alive by caches, globals or closures, not from the collector itself.