Use Weak References for Nonowning Relationships
Core idea
A weak reference observes an object without keeping it alive. Call weakref.ref once and keep the result in a local variable while using it; None means the referent is gone. WeakValueDictionary drops entries when values die. Not every type supports weak references.
import weakrefclass Entry: passx=Entry(); r=weakref.ref(x)current=r()if current is not None: print(current is x)The local name keeps the object alive while working with it.
Expected output:
TrueObserve a weak cache
import weakref, gcclass Entry: passx=Entry(); cache=weakref.WeakValueDictionary()cache['a']=xprint('a' in cache)del x; gc.collect()print('a' in cache)The cache is not an owner; on this CPython fixture the entry disappears after the last strong reference is removed.
Expected output:
TrueFalseCommon mistake
Do not call r() twice across a check and use; another thread could release the object. Do not assume eviction timing on all runtimes.
Practice
Try weakref.ref on a list and on a user-defined object; explain the TypeError and compare weak versus strong cache ownership.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Weak references
Check your understanding of weak references.
What is printed?
import weakrefclass A: passa=A(); r=weakref.ref(a)print(r() is a)What is printed?
import weakreftry: weakref.ref([])except TypeError: print("unsupported")Does a weak reference keep its referent alive?
How should a live referent be used safely?