Python › Memory Management & Garbage Collection

How does the weakref module help avoid reference cycles and memory leaks?

Advanced

Answer

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 alive
Real-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.

Common follow-ups: What's the difference between weakref.ref and weakref.proxy?;How does WeakValueDictionary use this internally?