How Python Manages Memory: Reference Counting and Garbage Collection

An examination of how CPython frees memory through reference counting and the cyclic garbage collector, with immortal objects, the incremental collector of Python 3.14, weak references and common pitfalls.

A green python with yellow markings coiled in interlocking loops, its head resting against its own body in warm light.
Photo by Oleksandr Sushko on Unsplash

Python programs rarely free memory explicitly, yet objects disappear as soon as they stop being needed. A useful image comes from online multiplayer games: the server keeps a match room open while at least one player remains connected, and it closes the room the moment the last player leaves. CPython treats every object in the same way, counting the references that point to it and releasing it when that count reaches zero. The image, however, ends where the interesting cases begin, because two objects can keep each other "connected" after every real reference has gone. The present article examines both mechanisms, reference counting and the cyclic garbage collector, which together form the secret weapon that spares Python programmers from manual memory management.

Reference Counting

Every object in CPython stores the number of references that point to it. Assigning the object to a name, placing it in a list or passing it to a function increments the count; deleting a name, removing the element or returning from the function decrements it. The function sys.getrefcount exposes this number, with the caveat that its own argument adds one temporary reference.

import sys

items = ["a", "b", "c"]
print(sys.getrefcount(items))  # Output: 2 (the name plus the argument)

alias = items
print(sys.getrefcount(items))  # Output: 3

del alias
print(sys.getrefcount(items))  # Output: 2

print(sys.getrefcount(None) > 1_000_000)  # Output: True

The last line reveals a detail introduced by PEP 683 in Python 3.12: None, True, small integers and other singletons are immortal objects, whose count is fixed at a very large value and never changes. Immortality avoids constant updates to objects that are shared by the whole interpreter and that must never be freed.

Immediate Destruction

The decisive property of reference counting is its timing: an object is destroyed at the exact moment its count reaches zero, without waiting for any separate process. The special method __del__, called just before destruction, makes this moment visible.

class Resource:
    def __init__(self, name):
        self.name = name

    def __del__(self):
        print(f"{self.name} released")

current = Resource("first")
current = Resource("second")  # Output: first released
print("after reassignment")   # Output: after reassignment
del current                   # Output: second released

The first object is released during the reassignment, before the following line runs, because the name current held its only reference. This determinism is the reason why CPython frees most objects promptly and with very short pauses.

Reference Cycles and the Cyclic Collector

Returning to the match room, a reference cycle resembles two bots that each count the other as a connected player: the room stays open although no human remains. In terms of objects, when a refers to b and b refers to a, both counts stay at one after every external name has been deleted, so reference counting alone can never free them. This is where the analogy ends, because Python has a second mechanism that detects such groups. The following example disables that mechanism temporarily to make the cycle visible.

import gc

class Node:
    def __init__(self, name):
        self.name = name
        self.partner = None

    def __del__(self):
        print(f"{self.name} destroyed")

gc.disable()
a, b = Node("A"), Node("B")
a.partner, b.partner = b, a
del a, b
print("references dropped, nothing destroyed yet")

found = gc.collect()  # Output: A destroyed, then B destroyed
print(f"collector found {found} unreachable objects")  # Output (CPython 3.12): 2
gc.enable()

Deleting the names destroys nothing, and only the explicit call to gc.collect() releases both nodes. The cyclic collector examines container objects, such as instances, lists and dictionaries, and finds groups that are reachable only from within themselves. Contrary to a widespread belief, objects that define __del__ are collected as well: PEP 442 removed that restriction in Python 3.4.

The organization of the collector changed in the version that was current at the date of this article. Up to Python 3.13, it divided container objects into three generations, based on the observation that most objects die young: new objects entered generation 0, which was examined often, and survivors moved to generations 1 and 2, which were examined less frequently. Python 3.14.0, released on 7 October 2025, replaced this design with an incremental collector that has only two generations, young and old, and examines the old generation in small increments, which substantially reduces the maximum pause in programs with large heaps.

The gc Module

The module gc gives access to the collector, and several of its functions are often misread. Its main operations are the following:

  1. gc.collect() runs a collection immediately and returns the number of unreachable objects it found.
  2. gc.get_threshold() returns the thresholds that trigger automatic collections.
  3. gc.get_count() returns the current counters compared with those thresholds, not the number of objects in each generation.
  4. gc.disable() and gc.enable() turn automatic collection off and on; reference counting continues in both cases.
  5. gc.freeze() moves every tracked object to a permanent generation that the collector ignores.
import gc

print(gc.get_threshold())  # Output (CPython 3.12): (700, 10, 10)
print(len(gc.get_count())) # Output: 3
print(gc.isenabled())      # Output: True
print(gc.is_tracked([]), gc.is_tracked(42))  # Output: True False

In Python 3.12, a collection of generation 0 starts when allocations minus deallocations of container objects exceed 700, and each older generation is examined after the younger one has been collected ten times. In Python 3.14, get_threshold() still returns three values, but the third one is always zero and has no meaning, and gc.collect(1) performs one increment instead of collecting a middle generation. The last line of the example shows that only containers are tracked: an integer cannot refer to other objects, so it can never be part of a cycle.

Breaking Cycles with Weak References

The cleanest way to avoid cycles is not to create them. A weak reference, provided by the module weakref, points to an object without increasing its count, so it is the standard tool for back-references such as a child that must know its parent.

import weakref

class Parent:
    def __init__(self):
        self.children = []

    def __del__(self):
        print("parent destroyed")

class Child:
    def __init__(self, parent):
        self._parent = weakref.ref(parent)
        parent.children.append(self)

    @property
    def parent(self):
        return self._parent()

parent = Parent()
child = Child(parent)
print(child.parent is parent)  # Output: True

del parent                     # Output: parent destroyed
print(child.parent)            # Output: None

The parent holds strong references to its children, while each child holds only a weak reference to its parent. Deleting the last strong reference destroys the parent immediately, without any intervention of the cyclic collector, and the weak reference returns None from then on. The module also offers WeakValueDictionary and WeakKeyDictionary, which suit caches that must not keep their entries alive.

Pitfalls of Memory Management

Automatic memory management removes most errors of manual allocation, but it introduces a few of its own. Five pitfalls are distinguished, which are the following:

  1. Resources released in __del__. The moment of destruction is immediate only when no cycle is involved, and other interpreters such as PyPy do not use reference counting at all. Files, sockets and locks should be released with a with statement, as described in the article devoted to context managers.
  2. Disabling the collector permanently. gc.disable() can shorten a critical section, but a long-running service that never re-enables it accumulates every cycle it creates.
  3. Exact reference counts in tests. The values of sys.getrefcount are an implementation detail; the documentation of Python 3.14 warns that they may be lower than before, because the interpreter now avoids some count updates.
  4. Hidden cycles. Exceptions stored in a variable keep the traceback, and the traceback keeps the frames with their local variables, which can include the variable itself; bound methods stored as callbacks keep their instance alive.
  5. Copy-on-write after fork. Updating reference counts writes to the memory of every object touched, so child processes created with fork gradually copy the pages they inherit; calling gc.freeze() before forking avoids the additional copies caused by the collector.

Measuring is preferable to guessing in all of these cases. The module tracemalloc, presented in the article devoted to profiling, shows which lines allocate the memory that remains alive, and the reduction of memory per instance is the subject of the article devoted to __slots__.

Choosing the Right Tool

Consequently, most programs need no intervention at all, and each tool of this article answers a specific situation. The following table summarizes the criteria.

Situation Recommended approach
Ordinary objects without cycles Nothing: reference counting frees them immediately
Files, sockets, locks and other external resources A with statement, never __del__
Back-references between parent and child, observers, caches weakref.ref, WeakValueDictionary or WeakKeyDictionary
Memory that grows without an obvious reason tracemalloc to locate the allocations, then gc.collect() to rule out cycles
Latency-sensitive sections in an application with many objects gc.disable() around the section, followed by gc.enable()
Pre-forking servers that load data before creating workers gc.freeze() before the fork

Conclusion

It is concluded that CPython manages memory through two complementary mechanisms: reference counting, which destroys each object at the exact moment its last reference disappears, and the cyclic collector, which finds groups of objects that keep each other alive. This magic explains why most objects vanish promptly, why cycles survive until a collection runs, and why weak references are the cleanest way to avoid those cycles. The collector itself evolved at the date of this article, from three generations to the incremental design of Python 3.14, while the principles remained the same. The global interpreter lock, which protects these reference counts from concurrent updates and which the free-threaded build of Python seeks to remove, is developed in a future article of this series.