Python weakref - caches and mappings that do not keep objects alive
Answer: For caches or mappings holding large objects, use the WeakKeyDictionary and WeakValueDictionary classes; register cleanup with finalize. A weak reference to an object is not enough to keep the object alive, so garbage collection can reclaim it and its entries in weak mappings are simply deleted.
Examples
import weakref
class Image:
def __init__(self, name):
self.name = name
cache = weakref.WeakValueDictionary()
img = Image("logo")
cache["logo"] = img
del img # entry disappears once collected
other = Image("banner")
r = weakref.ref(other)
obj = r() # None once the referent is gone
weakref.finalize(other, print, "cleaned up")
Tools
| Class or function | Returns | |---|---| | ref(obj[, callback]) | weak reference; call it to get the object, or None if no longer alive | | WeakValueDictionary | mapping class that references values weakly | | WeakKeyDictionary | mapping class that references keys weakly; attach data to objects owned elsewhere | | WeakSet | set interface with weak references to its elements | | WeakMethod | weak reference to a bound method | | finalize(obj, func, ...) | callable finalizer called when obj is garbage collected |
Rules
- Most programs only need the weak container types or
finalize; creating your own weak references directly is not usually necessary. - Not all objects can be weakly referenced. Class instances, Python functions, sets, generators and sockets can;
listanddictneed subclassing, andtupleandintdo not support it even when subclassed (CPython). - A plain
refto a bound method dies at once because a bound method is ephemeral; useWeakMethod. - Weak references are hashable if the object is hashable.
See also
Claims
- id: C1 claim: A weak reference alone does not keep an object alive. source: S1 evidence: "A weak reference to an object is not enough to keep the object alive"
- id: C2 claim: Weak references are hashable if the object is hashable. source: S1 evidence: "Weak references are hashable if the object is hashable."
- id: C3 claim: WeakValueDictionary references values weakly. source: S2 evidence: "Mapping class that references values weakly."
Sources
- [S1] weakref - Weak references. Python docs. https://docs.python.org/3/library/weakref.html . License: PSF-2.0. Accessed 2026-11-18.
- [S2] Lib/weakref.py. python/cpython (GitHub). https://github.com/python/cpython/blob/main/Lib/weakref.py . License: PSF-2.0. Accessed 2026-11-18.
License: this note is CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Summary by iinventedlight (AI-assisted). Sources: Python docs, weakref - Weak references; python/cpython (GitHub), Lib/weakref.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation. Text was condensed and changed from the originals.
License: CC-BY-4.0 · Summary by iinventedlight (AI-assisted). Sources: Python docs, weakref - Weak references; python/cpython (GitHub), Lib/weakref.py. PSF-2.0 (https://docs.python.org/3/license.html). Copyright Python Software Foundation.
Cite this
iinventedlight. 2026. "Python weakref - caches and mappings that do not keep objects alive." iinventedlight Library, iil:note:0zn6seme, version of 2026-11-18. https://iinventedlight.com/library/notes/python-weakref/. License: CC-BY-4.0.
@misc{iil_note_0zn6seme,
author = {{iinventedlight}},
title = {{Python weakref - caches and mappings that do not keep objects alive}},
howpublished = {iinventedlight Library},
year = {2026},
date = {2026-11-18},
url = {https://iinventedlight.com/library/notes/python-weakref/},
note = {Permanent ID iil:note:0zn6seme. License: CC-BY-4.0.},
}
Spotted a mistake? Use the MCP feedback tool or email hello@iinventedlight.com. Or Report a correction (no account needed).
Extra files beside this note
These files use this note's license, shown below. Paper extras retain their reproduction status; a link is not a reproduction.
- python-weakref.table.json (table; CC-BY-4.0)
- python-weakref.schema.json (schema; CC-BY-4.0)
For language models and agents: start at /llms.txt | /agents.md | /.well-known/agent-library.json. This page in Markdown: /library/notes/python-weakref.md.