Table of Contents

Python weakref

Python weakref provides references to objects that don't prevent garbage collection. If you hold a weak reference to an object and nothing else references it, the object is freed and the weak reference becomes invalid.

Use weak references to break circular references, implement caches that don't keep objects alive, or monitor when objects are deleted.

Example

This example shows weak references breaking a circular reference that would otherwise create a memory leak.

# run: python3 weakref.py
# description: weak references for circular reference management
 
import weakref
 
class Parent:
    def __init__(self, name):
        self.name = name
        self.children = []
 
    def add_child(self, child):
        self.children.append(child)
        child.parent = weakref.ref(self)  # weak reference to parent
 
class Child:
    def __init__(self, name):
        self.name = name
        self.parent = None
 
    def parent_name(self):
        if self.parent is None:
            return "no parent"
        parent_obj = self.parent()  # call weak ref to get object
        if parent_obj is None:
            return "parent was deleted"
        return parent_obj.name
 
# Create parent and child
p = Parent("Alice")
c1 = Child("Bob")
c2 = Child("Carol")
p.add_child(c1)
p.add_child(c2)
 
print(f"c1 parent: {c1.parent_name()}")
print(f"c2 parent: {c2.parent_name()}")
 
# Delete parent; weak ref becomes invalid
del p
print(f"after deletion: {c1.parent_name()}")
 
# With strong refs (circular), memory would leak
# With weak refs, parent can be garbage collected

Common patterns

Creating weak references:

Callback on deletion:

Weak value dictionaries:

Weak key dictionaries:

When to use:

Limitations: