import sysclassDemo:passobj =Demo()print(sys.getrefcount(obj))# Get reference countref = objprint(sys.getrefcount(obj))# Reference count increases with another referencedel refprint(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.
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.")