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

Copy

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

Copy

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

Copy


4. Weak References in a Dictionary

Copy


5. Weak References and Cyclic Garbage Collection

Copy


6. Weak References with Custom Objects

Copy


7. Tracking Object Lifecycle with Weak References

Copy


8. Using WeakSet

Copy


9. Preventing Reference Count Increments

Copy


10. WeakValueDictionary for Cache Management

Copy


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