28. Weak References
This Python code snippets demonstrates the use of the weakref module to manage objects without increasing their reference count:
import weakref
class Demo:
pass
obj = Demo()
weak_ref = weakref.ref(obj) # Create a weak reference
print("Object via weak reference:", weak_ref()) # Access the object
del obj # Delete the strong reference
print("Object after deletion:", weak_ref()) # None: object has been garbage collectedimport weakref
class Demo:
def greet(self):
return "Hello!"
obj = Demo()
proxy = weakref.proxy(obj) # Create a proxy weak reference
print(proxy.greet()) # Access methods via the proxy
del obj
try:
print(proxy.greet()) # Raises ReferenceError since the object is gone
except ReferenceError:
print("Object has been garbage collected.")Last updated