Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Standard Library: Data Structures and Functional Tools

The weakref module

Reference for Python's weakref module: ref, proxy, WeakValueDictionary, WeakSet, WeakKeyDictionary, finalize and which objects can be weakly referenced.

A normal reference keeps an object alive: as long as some variable, list or attribute points at it, Python will not free it. A weak reference points at an object without counting toward that. When the last normal reference disappears, the object is destroyed and the weak reference becomes "dead".

The weakref module provides weak references and containers built on them. They are the right tool for caches that should not prevent cleanup, for observer lists that should forget listeners when those are deleted, and for parent links in trees that would otherwise create reference cycles.

Python
import weakref

ref = weakref.ref(obj)   # call ref() to get obj back, or None if it is gone

Try it

Python ref, proxy and finalize

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python WeakValueDictionary and WeakSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

What is in the module

Name Description
ref(obj, callback=None) Weak reference. Call it to get the object or None. The optional callback receives the dead reference object.
proxy(obj, callback=None) An object that forwards attribute access to the referent; raises ReferenceError once the referent is gone.
WeakValueDictionary Dict whose values are weakly held; entries disappear when a value dies.
WeakKeyDictionary Dict whose keys are weakly held.
WeakSet Set whose members are weakly held.
WeakMethod(method) Weak reference to a bound method (a plain ref to a bound method would die immediately).
finalize(obj, func, *args, **kwargs) Registers a cleanup call for when obj is collected; call it early with fin(); check fin.alive.
getweakrefcount(obj) Number of weak references to obj.

Usage notes

  • Not every object supports weak references. int, str, tuple, list and dict instances do not, but their subclasses do. Instances of your own classes do, unless the class defines __slots__ without "__weakref__".
  • Always check the result. r() can return None; keep the result in a local variable (obj = r()) and test it once, rather than calling r() twice.
  • Timing is an implementation detail. CPython frees an object at once when its reference count drops to zero, but objects in cycles wait for the garbage collector; other implementations differ. Examples call gc.collect() to be deterministic.
  • Prefer finalize over __del__. It is safer in cycles, runs at most once, and by default runs at interpreter exit. The callback must not reference the object itself, or the object never dies.
  • Hashing. WeakKeyDictionary and WeakSet need hashable objects. A ref is hashable if the referent is.
  • Iterating weak containers while objects die can shrink them mid-loop; iterate over list(container) when you need a stable snapshot.
  • Caches: functools.lru_cache keeps strong references. For "cache while someone else is using it", use WeakValueDictionary.
  • Reference counting is covered in the memory management lesson.