garbage collection
In Python, garbage collection (sometimes abbreviated as GC) is an automatic memory management feature that reclaims memory occupied by objects that are no longer being used by your program. It helps you manage memory allocation and deallocation without having to manually free up memory, which can be error-prone and tedious.
Python’s garbage collector primarily uses reference counting to track and clean up unused objects. When an object’s reference count drops to zero, it means that the object is no longer accessible, and its memory can be reclaimed.
Python also employs a cyclic garbage collector to handle reference cycles, which occur when objects reference each other, creating a loop. This situation can prevent the reference count from dropping to zero, so the cyclic garbage collector identifies these loops and cleans them up to free memory.
Example
Here’s an example demonstrating Python’s cyclic garbage collector. Two objects reference each other, creating a cycle that reference counting alone can’t clean up:
>>> import gc
>>> class Node:
... def __init__(self, name):
... self.name = name
... self.other = None
... def __del__(self):
... print(f"Node({self.name!r}) deleted")
...
>>> a = Node("A")
>>> b = Node("B")
>>> a.other = b
>>> b.other = a # Creates a reference cycle
>>> del a, b # Ref counts don't reach zero — the cycle keeps both alive
>>> gc.collect() # The cyclic GC detects and breaks the cycle
Node('A') deleted
Node('B') deleted
...
In this example, deleting a and b doesn’t free the objects because each one still holds a reference to the other. The cyclic garbage collector identifies this loop and reclaims both objects. In most code, reference counting handles cleanup immediately when an object’s reference count drops to zero. The cyclic collector runs periodically to catch cases like this.
Related Resources
Tutorial
Memory Management in Python
Get ready for a deep dive into the internals of Python to understand how it handles memory management. By the end of this article, you’ll know more about low-level computing, understand how Python abstracts lower-level operations, and find out about Python’s internal memory management algorithms.
For additional information on related topics, take a look at the following resources:
- How Python Manages Memory (Course)