27. Python's Garbage Collection

This Python code snippets demonstrating concepts related to Python's garbage collection and memory management:


1. Manually Triggering Garbage Collection

import gc

class Demo:
    def __del__(self):
        print("Object destroyed.")

obj = Demo()
del obj  # Object eligible for garbage collection
gc.collect()  # Manually trigger garbage collection

2. Reference Counting

import sys

class Demo:
    pass

obj = Demo()
print(sys.getrefcount(obj))  # Get reference count
ref = obj
print(sys.getrefcount(obj))  # Reference count increases with another reference
del ref
print(sys.getrefcount(obj))  # Reference count decreases after deletion

3. Cyclic References


4. Disabling Garbage Collection


5. Tracking Unreachable Objects


6. Weak References


7. Customizing Object Finalization with __del__


8. Memory Management with Generations


9. Viewing Objects in Garbage


10. Memory Management with id and del


These snippets illustrate Python's garbage collection mechanisms, including reference counting, cyclic garbage collection, weak references, and manual garbage collection controls. This understanding helps optimize memory usage and avoid common pitfalls like memory leaks.

Last updated