Python › Memory Management & Garbage Collection
How does the weakref module help avoid reference cycles and memory leaks?
AdvancedAnswer
weakref.ref (and weakref.proxy) creates a reference to an object that doesn't increase its reference count, so the referenced object can still be garbage collected even while the weak reference exists (in which case it becomes None or raises ReferenceError). This is useful for caches, observer patterns, or parent-child relationships where you want a back-reference without preventing cleanup.
import weakref
class Parent:
def __init__(self):
self.children = []
class Child:
def __init__(self, parent):
self.parent = weakref.ref(parent) # doesn't keep parent alive
p = Parent()
c = Child(p)
print(c.parent()) # <Parent object> while p is aliveReal-world example An event-listener system stores weak references to subscriber objects so subscribers can be garbage collected normally when no longer used elsewhere, instead of being kept alive forever just because they're registered as listeners.