Garbage Collection in Python

Garbage collection is a process of automatically identifying and reclaiming memory that is no longer in use or needed by a program. In Python, garbage collection helps manage memory by cleaning up objects that are no longer accessible, preventing memory leaks and optimizing memory usage.

Key Features of Garbage Collection:

How Garbage Collection Works:

Python's garbage collection process consists of two main components:

Example of Garbage Collection

This example demonstrates how reference counting works in Python. When an object is no longer referenced, it is automatically deallocated.

Code Example

import gc
        
        class MyClass:
            def __init__(self, name):
                self.name = name
        
        # Creating an object of MyClass
        obj = MyClass("Example")
        
        # Checking the reference count
        print("Reference count before deletion:", gc.get_referrers(obj))
        
        # Deleting the object
        del obj
        
        # Forcing garbage collection
        gc.collect()
        
        print("Garbage collection completed.")
        

Output

Reference count before deletion: [
<class '__main__.MyClass'>
]
Garbage collection completed.

Conclusion

Garbage collection in Python is a crucial feature that helps manage memory automatically. By utilizing reference counting and cyclic garbage collection, Python ensures efficient memory use and reduces the risk of memory leaks, allowing developers to focus on building robust applications.