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

Copy

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

Copy

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

Copy


4. Disabling Garbage Collection

Copy


5. Tracking Unreachable Objects

Copy


6. Weak References

Copy


7. Customizing Object Finalization with __del__

Copy


8. Memory Management with Generations

Copy


9. Viewing Objects in Garbage

Copy


10. Memory Management with id and del

Copy


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