28. Weak References

This Python code snippets demonstrates the use of the weakref module to manage objects without increasing their reference count:


1. Creating a Weak Reference

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 collected

2. Using weakref.proxy

import 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.")

3. Weak Reference Callbacks


4. Weak References in a Dictionary


5. Weak References and Cyclic Garbage Collection


6. Weak References with Custom Objects


7. Tracking Object Lifecycle with Weak References


8. Using WeakSet


9. Preventing Reference Count Increments


10. WeakValueDictionary for Cache Management


These examples illustrate how the weakref module can be used to manage object lifetimes without increasing reference counts, enabling efficient memory management and avoiding memory leaks caused by cyclic references.

Last updated