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 weakrefclassDemo:passobj =Demo()weak_ref = weakref.ref(obj)# Create a weak referenceprint("Object via weak reference:", weak_ref())# Access the objectdel obj # Delete the strong referenceprint("Object after deletion:", weak_ref())# None: object has been garbage collected
2. Using weakref.proxy
import weakrefclassDemo:defgreet(self):return"Hello!"obj =Demo()proxy = weakref.proxy(obj)# Create a proxy weak referenceprint(proxy.greet())# Access methods via the proxydel objtry:print(proxy.greet())# Raises ReferenceError since the object is goneexceptReferenceError: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.
import weakref
class Demo:
pass
def on_finalize(weak_ref):
print("Object has been finalized and garbage collected.")
obj = Demo()
weak_ref = weakref.ref(obj, on_finalize) # Attach a callback
del obj # Triggers the callback
import weakref
class Demo:
def __init__(self, name):
self.name = name
obj1 = Demo("Object1")
obj2 = Demo("Object2")
weak_dict = weakref.WeakValueDictionary()
weak_dict["key1"] = obj1
weak_dict["key2"] = obj2
print("Before deletion:", weak_dict.keys())
del obj1
print("After deletion of obj1:", weak_dict.keys())
import gc
import weakref
class Demo:
pass
a = Demo()
b = Demo()
a.ref = b
b.ref = weakref.ref(a) # Use weak reference to break the strong reference cycle
del a
del b
print("Unreachable objects:", gc.collect())
import weakref
class Custom:
def __init__(self, value):
self.value = value
obj = Custom(42)
weak_ref = weakref.ref(obj)
print("Value via weak reference:", weak_ref().value)
del obj
print("After deletion:", weak_ref())
import weakref
class Demo:
def __del__(self):
print("Demo object deleted.")
obj = Demo()
weak_ref = weakref.ref(obj)
print("Object exists:", weak_ref() is not None)
del obj
print("Object after deletion:", weak_ref())
import weakref
class Demo:
def __init__(self, name):
self.name = name
obj1 = Demo("Obj1")
obj2 = Demo("Obj2")
weak_set = weakref.WeakSet([obj1, obj2])
print("WeakSet contents:", [obj.name for obj in weak_set])
del obj1
print("After deletion of obj1:", [obj.name for obj in weak_set])