Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Memory & performanceSeniorCommonTheory

How does CPython primarily manage memory, and what problem does reference counting alone fail to solve?

Answer

In the default CPython build, every object carries a reference count, incremented whenever a new reference to it is created and decremented whenever a reference goes away; when the count reaches zero, the object's memory is freed immediately and deterministically. This handles most memory cleanup cheaply and predictably for ordinary objects, but it cannot free objects that reference each other in a cycle — like two objects that hold references to one another — because neither one's count ever naturally reaches zero even after nothing external references either of them. Python 3.14's free-threaded build relaxes some of that immediacy: certain frequently-shared objects are made "immortal" and never freed via refcounting at all, and the build's deferred, per-thread reference counting combined with a technique called QSBR (quiescent-state-based reclamation) means an object's memory is not always reclaimed the instant its count would logically reach zero, trading some of that determinism for lower cross-thread synchronization overhead.

Strong answer includes

  • reference count tracked per object in the default build, freed immediately at zero for ordinary objects
  • cannot free reference cycles on its own
  • free-threaded 3.14 uses immortal objects and deferred per-thread refcounting (QSBR), relaxing strict immediacy

Practical example

Two nodes of a doubly-linked list that reference each other as `next` and `prev` will never reach a reference count of zero on their own, even after the list itself is deleted, unless something else steps in to break the cycle.

#memory-management#cpython-internals

Sources

gc — Garbage collector interfacePython Software Foundation · Generational garbage collection and cyclic-reference behaviorThe Python Standard LibraryPython Software Foundation · Authoritative behavior for built-in types and standard library modules