Garbage Collection

In Python, garbage collection is an automatic memory management feature that reclaims memory occupied by objects that are no longer in use 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 garbage collection. Note that the example uses gc.collect() to force the garbage collection, which normally runs automatically but may not be immediately:

Python
>>> import weakref
>>> import gc

>>> class Number:
...     def __init__(self, value):
...         self.value = value
...         print(f"Object '{self!r}' created.")
...     def __del__(self):
...         print(f"Object '{self!r}' deleted.")
...     def __repr__(self):
...         return f"Number(value={self.value})"
...

>>> number = Number(42)
Object 'Number(value=42)' created.

>>> weak_ref = weakref.ref(number)
>>> # Check if the weak reference still points to the object
>>> weak_ref() is not None
True

>>> # Delete the object
>>> del number
Object 'Number(value=42)' deleted.

>>> # Force garbage collection
>>> gc.collect()
8

>>> # Check if the weak reference still points to the object
>>> weak_ref() is not None
False

In this example, you create the number object and then delete it using the del statement. Once number is deleted, the reference count drops to zero, allowing the garbage collector to reclaim the memory.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Dec. 19, 2024 • Reviewed by Dan Bader