Lesson · Copying, Memory & Object Lifecycle
Weak References
75 min readWeak References
Weak references observe objects without keeping them alive. They support caches, registries, and observer relationships where ownership must remain elsewhere.
Learning goals
- Create a weak reference with
weakref.refand fetch its target, including theNoneresult after the target dies. - Explain the difference between a strong and a weak reference using ownership rather than syntax.
- Watch a weak dictionary drop an entry automatically when its last strong owner disappears.
- Recognize the object shapes that cannot carry weak references and say why.
- Choose a cache or observer design where ownership stays with the caller.
Mental model
A weak reference changes only the ownership side of the picture: the connection is visible while the target lives, and it becomes dead, not dangling, once the last strong owner leaves. That is what separates a cache entry from an owner.
Mental model
read it top to bottom
strong reference: owner → target (keeps the target alive) weak reference: observer → target (target free to die, handle then returns None)
Core idea
A weak reference points at an object while declaring that the pointer must not extend the object's life: when the last strong reference disappears, the weak handle starts returning None instead of keeping a dead object around. Caches, registries, and observers use this to watch objects without owning them, so the last real user decides when everything is released.
weakref
The weakref module creates references that do not increase an object's strong-reference count. A weak reference becomes dead when the target has no strong owners.
Weak references
A weak reference is a handle created with weakref.ref(target) that does not count toward the target's lifetime; calling the handle returns the object or None once it is gone. Because the target can die at any time, code should fetch it into a local name and check for None before using it.
Weak dictionaries
Weak containers hold entries without keeping referenced objects alive. Entries disappear automatically when the remaining strong owners are gone.
Weak sets
Weak containers hold entries without keeping referenced objects alive. Entries disappear automatically when the remaining strong owners are gone.
Cache / observer use cases
A cache that stores only weak references lets entries vanish when callers drop their own references, so the cache can never hold a workload alive by itself. Observer and listener lists work the same way: a subject must not keep every listener breathing forever just because someone subscribed.
Walkthrough
image = Image()creates the only strong reference;weakref.ref(image)builds a handle whose lifetime behavior is the whole subject of the lesson.reference() is imageprints True while the strong name exists: calling the handle fetches the live target, and identity is preserved.del imageremoves the last strong owner, so the object is reclaimed and the secondreference()call returnsNoneinstead of a dead object.- Predict before running: both printed values, and what a second strong name (
alias = image) would change about the second print.
Experiments to try
- Add
alias = imagebefore thedel, delete onlyimage, and printreference() is alias; the handle stays alive while any strong owner remains. - Call
weakref.ref(42)and read theTypeError, then create a slotted class without__weakref__and observe the same restriction. - Print
weakref.getweakrefcount(image)after one handle and after two; state what the count includes. - Build a
WeakValueDictionary, store one object under a key, delete the last strong name, and printlen(store); the entry disappears with no cleanup call.
Common mistakes
- Relying on a weak cache to keep data available: if nothing else holds the object, the entry vanishes, because weak references observe ownership, they do not replace it.
- Treating the handle as the object:
reference.attrfails, and the target must be fetched by calling the handle first, or aweakref.proxyused in its place. - Assuming every object supports weak references: built-in scalars like
intandstrraiseTypeError, and slotted classes need__weakref__declared. - Calling the handle twice around a check (
if ref() is not None: ref().run()): the object returned by the first call is temporary and can be gone by the second call, so fetch once into a local name.
Practice: Easy
- Run the worked example and write down both prints; then create a new
Imageunder the same name and confirm the old handle still returnsNone. - Add
alias = imagebefore thedeland verify the handle survives; then delete both names and check the handle again. - Ask a weak handle for its target twice while a strong name exists (
reference() is reference()) and explain the result with identity.
Practice: Medium
- Build a
WeakValueDictionarycache keyed by name; delete the last strong reference and show the entry disappears, then add an external owner and show it stays. - Compare
weakref.refwithweakref.proxy: call the same method through both, then delete the target and read theReferenceErrorthat the proxy raises. - Print
weakref.getweakrefcount(image)after creating one handle and again after a second handle plus a proxy; state what the count includes.
Practice: Hard
- Write an observer list that stores listeners weakly and skips dead entries when notifying; test it with a listener that is deleted between two notifications.
- Set up a failure lab with three broken builds: a handle used after its target is collected, the twice-called handle pattern, and a
TypeErrorfrom weakly referencing an unsupported type; explain each from the lifetime rule. - Design an object registry for a long-running process: decide when entries may vanish (last strong owner gone), what
lookupreturns for a missing entry, and how tests avoid depending on collection timing.
Lesson checklist
- I can create a weak reference, fetch its target, and handle the
Nonecase. - I can explain ownership in one sentence: which reference keeps the object alive and which only observes.
- I can let a weak dictionary entry disappear without writing cleanup code.
- I can name two kinds of objects that refuse weak references and why.
Remember
Weak references add an observing edge to the object graph without extending any lifetime: the handle returns the target while a strong owner exists and `None` afterward. That makes them the right tool for caches, registries, and observers, provided code fetches the target into a local name before use and never mistakes observation for ownership.
Interview angles
What is the main purpose of **weakref**?+
The weakref module creates references that do not increase an object's strong-reference count. A weak reference becomes dead when the target has no strong owners.
What should you pay attention to when using **Weak references**?+
A weak reference is a handle created with weakref.ref(target) that does not count toward the target's lifetime; calling the handle returns the object or None once it is gone. Because the target can die at any time, code should fetch it into a local name and check for None before using it.
How does **Weak dictionaries** fit into this lesson?+
Weak containers hold entries without keeping referenced objects alive. Entries disappear automatically when the remaining strong owners are gone.
Why can `reference()` return `None` even though it returned the object a line earlier?+
The handle only observes; once the last strong reference is gone, the target is reclaimed and every weak handle to it starts returning None immediately. Nothing about the handle itself keeps the object alive.