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.
import gc
class A:
def __init__(self):
self.ref = None
a = A()
b = A()
a.ref = b
b.ref = a # Creates a reference cycle
del a
del b
# Objects won't be freed immediately due to the cycle, but garbage collector will handle it
gc.collect()
import gc
class Demo:
pass
a = Demo()
b = Demo()
a.ref = b
b.ref = a # Cyclic reference
del a
del b
unreachable = gc.collect() # Trigger garbage collection
print(f"Unreachable objects collected: {unreachable}")
import weakref
class Demo:
pass
obj = Demo()
weak_ref = weakref.ref(obj) # Create a weak reference
print(weak_ref()) # Access the object via weak reference
del obj # Delete the strong reference
print(weak_ref()) # None: object has been garbage collected
class Demo:
def __del__(self):
print(f"Instance of {self.__class__.__name__} deleted.")
obj = Demo()
del obj # __del__ is called when the object is destroyed
import gc
gc.set_debug(gc.DEBUG_LEAK) # Enable debug mode
print("Garbage collection thresholds:", gc.get_threshold()) # Get thresholds for generations
# Set custom thresholds
gc.set_threshold(100, 10, 10)
print("Updated thresholds:", gc.get_threshold())
import gc
class Demo:
pass
a = Demo()
b = Demo()
a.ref = b
b.ref = a # Cyclic reference
del a
del b
gc.collect()
print("Garbage objects:", gc.garbage)
class Demo:
pass
obj = Demo()
print(f"Object ID before deletion: {id(obj)}")
del obj
try:
print(f"Object ID after deletion: {id(obj)}")
except NameError:
print("Object no longer exists.")