Sub topic 6
Weak references
This chapter assumes you know how reference counting frees objects and that a name bound to an object is a strong reference. A strong reference keeps an object alive. A weak reference lets you reach an object without keeping it alive.
What a weak reference does
A weak reference is an object that points to a target without increasing the target's reference count. When the last strong reference to the target disappears, CPython frees the target. The weak reference then reports that the target is gone.
import weakref
class Resource:
pass
obj = Resource()
ref = weakref.ref(obj)
print(ref() is obj) # True
del obj
print(ref()) # None in CPython, because the last strong reference is goneCalling ref() returns the target if it is still alive, or None if it has been freed. Always check the result before you use it.
Why you would use one
You use a weak reference when you want to look up an object if it still exists, but you do not want your lookup to be the reason it exists. Two common cases are caches and back-pointers.
- A cache of expensive objects should not keep them alive after every other user has finished with them.
- A child that points back to its parent should not keep the parent alive. A strong back-pointer creates a reference cycle, which only the cyclic collector can free.
Weak collections
Handling many weak references by hand is tedious. The weakref module provides WeakValueDictionary and WeakKeyDictionary. They drop an entry automatically when the value (or key) is freed.
import weakref
class Image:
def __init__(self, name):
self.name = name
cache = weakref.WeakValueDictionary()
def load(name):
img = cache.get(name)
if img is None:
img = Image(name)
cache[name] = img
return img
a = load("logo")
b = load("logo")
print(a is b) # True: the second call reused the cached object
del a, b
print(len(cache)) # 0 in CPython: the entry vanished with the last strong referenceWhile any caller holds the image, load returns the same object. When all callers let go, the cache forgets it.
Cleanup without `__del__`
weakref.finalize runs a function when an object is freed, and it avoids many of the problems of __del__. The callback must not refer to the object itself, or it would keep the object alive.
import weakref
class Connection:
pass
def close(name):
print("closing", name)
conn = Connection()
weakref.finalize(conn, close, "db")
del conn # prints: closing dbWhat cannot be weakly referenced
Not every object supports weak references. Instances of plain list, dict, int, and str do not. Subclasses of list and dict do, and so do ordinary class instances.
import weakref
try:
weakref.ref([1, 2, 3])
except TypeError as e:
print(e) # cannot create weak reference to 'list' objectA class that defines __slots__ without __weakref__ also rejects weak references. Add "__weakref__" to the slots if you need them.
Common errors
- Using
ref()without checking forNone. The target may already be gone. - Creating a weak reference to a temporary, such as
weakref.ref(Resource()). No strong reference exists, so the object is freed at once. - Assuming the target is freed immediately on every Python implementation. The immediate freeing shown here is CPython's reference counting. Other implementations may free it later.
- Having a finalizer callback capture the target. This keeps the target alive, so the callback never runs.
Exercise
You store Image objects in a regular dict used as a cache, and memory keeps growing even after all other code has dropped its references. What change makes entries disappear when no one else uses the images, and what must callers check when reading from the cache?
Show answer
Replace the dict with weakref.WeakValueDictionary. The dictionary holds only weak references to its values, so an entry is removed when the last outside strong reference to that image is gone. Callers must handle a missing key, for example with cache.get(name) returning None, and then rebuild the object, because an entry can disappear at any time.