Table of Contents


Memory management in CPython

CPython uses two complementary mechanisms:

  • Reference counting — every object tracks how many names point to it; when the count hits zero, the object is freed immediately.
  • Generational garbage collection — a fallback that finds circular references, which reference counting alone can never free.
import platform
 
platform.python_implementation()

Output:

'CPython'

Which implementation are you running?

Reference counting is a CPython (and PyPy-compatible) implementation detail, not part of the Python language specification. Other runtimes may differ.

Reference counting

import sys
 
sys.getrefcount(257)

Output:

3

getrefcount lies by one

The argument itself is a temporary reference inside the call, so the reported number is one higher than the “real” count. Passing a literal (which the compiler interns) makes the number even less predictable — treat it as an order-of-magnitude probe, not an exact value.

Interned small integers

CPython caches integers in [-5, 256] — every name for such a value points to the same object. 257 sits just above the cache, so each literal evaluation creates a distinct object.

x = 257
y = x
t = 257
z = t
print(id(x), id(y), id(t), id(z))

Output (ids vary per run):

134483333406768 134483333406768 134483333406512 134483333406512

Two ids, not four

x/y share one id (same object, two references), t/z share another — the literal 257 was evaluated twice, in two code constants. Replace 257 with 256 and all four ids become equal, because small integers are interned. Never rely on id() for equality; use ==.

What is a Reference Cycle?

A list containing itself — the classic infinite regress. Reference counting can never free it: every element always has at least one reference (from the container itself).

a = []
for _ in range(10):
    a.append(a)
 
a

Output:

[[...], [...], [...], [...], [...], [...], [...], [...], [...], [...]]
sys.getrefcount(a)

Output:

17

Why 17?

One reference from the global name a, one from the function call, one from the outer list cell… plus the repr machinery. The exact number is irrelevant — the point is that the count never reaches zero, no matter how many names go out of scope. Only the generational GC can break the cycle.

Parent/Child cycle

__del__ is called when the object is destroyed — a visible trace of collection.

class Parent:
    def __init__(self, *children):
        self.children = list(children)
        for child in self.children:
            child.parent = self
 
    def __del__(self):
        print("Removing {__class__.__name__} {id:d}".format(
            __class__=self.__class__, id=id(self)))
 
 
class Child:
    def __del__(self):
        print("Removing {__class__.__name__} {id:d}".format(
            __class__=self.__class__, id=id(self)))

Case 1 — no cycle: acyclic objects are freed by reference counting, immediately.

p = Parent()
id(p)

Output:

128908629541504
del p

Output:

Removing Parent 128908629541504

Case 2 — cyclic: the children hold parent, the parent holds children.

p = Parent(Child(), Child())
id(p)

Output:

128908629548896
sys.getrefcount(p)

Output:

4

The cycle outlives the del

del p drops your reference, but each child still points at the parent — the object group is unreachable yet uncountable-to-zero. It survives until the next generational collection. Forgetting the children, on reassignment, makes the group collectible:

p = Parent()   # old Parent + 2 Children now unreachable as a cycle
del p

Output:

Removing Parent 128908629367280

Preventing cycles by design

Use weakref (or weakref.WeakKeyDictionary) for the back-reference child.parent = self. A weak reference does not increase the refcount, so the child no longer keeps the parent alive — the cycle never forms.

The generational garbage collector

The three generations

  • Generation 0 — newly created objects are kept in this list. Collected most often.
  • Generation 1 — objects moved here when they survive a collection a couple of times and are still referenced.
  • Generation 2 — the oldest objects; collected least often, on the assumption that long-lived objects stay alive (the weak generational hypothesis).

Inspecting the GC with gc

l = [1, 2, 3]
# p = l
import gc
 
gc.get_count()

Output:

(111, 1, 0)
gc.get_threshold()

Output:

(700, 10, 10)

Reading the numbers

get_count() = (objects in gen 0, gen 1, gen 2). get_threshold() = (700, 10, 10): a generation 0 collection runs every 700 new allocations; a gen-1 collection runs after 10 gen-0 passes, and gen-2 after 10 gen-1 passes. The tuple changes if a collection just ran.

gc.collect()

Output:

1

What does the return value mean?

gc.collect() returns the number of unreachable objects found (cycles collected). It runs a full collection of all generations — expensive, so never call it in a loop to “clean up”; CPython’s automatic schedule is usually the right policy.