python / expert
Snippet
Memory-Efficient Caching with WeakRef
A WeakValueDictionary holds 'weak' references to its values. If an object is no longer referenced anywhere else in the program, the garbage collector can delete it even if it is still a value in the dictionary, automatically preventing memory leaks in caches.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
import weakrefclass DataBlob:def __init__(self, data): self.data = datacache = weakref.WeakValueDictionary()blob = DataBlob("heavy-data")cache["key"] = blobprint("Cached:", "key" in cache)del blobprint("After del:", "key" in cache)
Breakdown
1
cache = weakref.WeakValueDictionary()
Creates a dictionary where values are garbage-collected if no strong references exist.
2
del blob
Removes the only strong reference, triggering immediate cleanup from the cache.