Weak References (weakref)
A weak reference points to an object without keeping it alive, so the garbage collector can reclaim that object as soon as every ordinary (strong) reference is gone.
Learn Weak References (weakref) in our free Python course — an interactive lesson with runnable examples, a practice exercise and a quick reference.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
The weakref module is the key to leak-free caches, observer patterns, and back-pointers — places where you want to refer to something without owning it.
weakref.ref(obj) returns a callable proxy: call it to get the object back, or None if the object has been collected. We use del plus gc.collect() to make the demo's collection happen deterministically :
A WeakValueDictionary holds its values weakly, so an entry automatically disappears once the value object is no longer used anywhere else. This is the classic way to build a cache that never leaks memory:
Contrast this with a normal dict : it would hold a strong reference, keeping every Image alive forever and slowly leaking memory. The weak dict lets unused entries evaporate on their own.
Sometimes you want to react when an object is reclaimed — to log it or release a resource. Pass a callback to weakref.ref(obj, callback) , or use the cleaner weakref.finalize(obj, func, *args) :
Fill in each ___ so the object is collected after del and the weak reference reports it. (Hint: the constructor is weakref.ref , and you force collection with gc.collect() .)
❌ Using a dead weakref without checking for None
❌ Trying to weakly reference a plain int, list, or tuple
✅ Use instances of your own classes (they support weakrefs)
❌ Expecting a weakref alone to keep the object alive
✅ Keep a strong reference for as long as you need the object
Build a tiny object cache with a WeakValueDictionary . Add three objects, drop the strong references to two of them, force collection, and show that only the still-referenced object remains.
Lesson complete — you manage memory like a pro!
You can create a weakref.ref that doesn't keep objects alive, build self-clearing caches with WeakValueDictionary , attach data via WeakKeyDictionary , and run cleanup callbacks with weakref.finalize — the tools that keep long-running programs leak-free.
🚀 Up next: a checkpoint — combine struct, statistics, textwrap, and the rest into one build challenge.
Practice quiz
What is a weak reference in Python?
- A reference that keeps an object alive twice as long
- A read-only copy of an object
- A reference that points to an object without keeping it alive
- A reference that only works for integers
Answer: A reference that points to an object without keeping it alive. A weak reference refers to an object but does NOT count toward keeping it alive, so it can be collected once strong references are gone.
Calling a dead weakref, ref(), returns what once the object has been collected?
- None
- The last value
- An empty string
- It raises KeyError
Answer: None. weakref.ref(obj) is callable; it returns the object, or None if the object has already been collected.
Which container holds its VALUES weakly, making it ideal for a self-clearing cache?
- WeakKeyDictionary
- OrderedDict
- defaultdict
- WeakValueDictionary
Answer: WeakValueDictionary. A WeakValueDictionary drops an entry when its value object is collected — perfect for caches keyed by an id.
What does WeakKeyDictionary hold weakly?
- Its values
- Its keys, so entries vanish when the key object is collected
- Both keys and values strongly
- Nothing — it is a normal dict
Answer: Its keys, so entries vanish when the key object is collected. A WeakKeyDictionary holds KEYS weakly; entries disappear when the key is collected — handy for attaching data to objects you don't own.
Why does this code raise a TypeError: weakref.ref([1, 2, 3])?
- Plain lists (and ints, tuples) don't support weak references
- Lists are too large to reference
- You must import list first
- The list is empty
Answer: Plain lists (and ints, tuples) don't support weak references. Built-in types like list, int, and tuple cannot be weakly referenced; instances of your own classes can.
In the demos, why are 'del obj' and 'gc.collect()' used together?
- Because weakref requires gc to be imported
- To create the weak reference
- To make collection happen deterministically so the output is predictable
- To convert the object to a string
Answer: To make collection happen deterministically so the output is predictable. del drops the last strong reference and gc.collect() forces collection immediately, making the weakref go dead deterministically.
Which is the recommended way to run cleanup code when an object is collected?
- Override __del__ on the class
- weakref.finalize(obj, func, *args)
- A while loop polling the object
- atexit.register
Answer: weakref.finalize(obj, func, *args). weakref.finalize is predictable, runs at most once, and avoids the pitfalls of __del__ (like accidentally keeping the object alive).
Why use weak references in a cache instead of a normal dict?
- A normal dict is slower to read
- Weak references compress the data
- Normal dicts cannot store objects
- A normal dict holds strong references and would keep every object alive, leaking memory
Answer: A normal dict holds strong references and would keep every object alive, leaking memory. A normal dict's strong references pin every cached object in memory; a WeakValueDictionary lets unused entries evaporate automatically.
Before using the result of obj = ref(), what should you always do?
- Sort it
- Check whether it is None, since the object may have been collected
- Convert it to a string
- Call gc.collect() on it
Answer: Check whether it is None, since the object may have been collected. Between two lines the object could be collected, so guard the dereferenced result: 'if obj is not None: ...'.
A weakref alone, with no strong reference, will:
- Keep the object alive forever
- Raise an error on creation
- Not keep the object alive — it may be collected immediately
- Make a deep copy of the object
Answer: Not keep the object alive — it may be collected immediately. A weakref does not count toward keeping an object alive; without a strong reference the object can vanish right away.