capypad
0 day streak
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
python
1
2
3
4
5
6
7
8
9
10
11
12
import weakref
 
class DataBlob:
def __init__(self, data): self.data = data
 
cache = weakref.WeakValueDictionary()
blob = DataBlob("heavy-data")
cache["key"] = blob
 
print("Cached:", "key" in cache)
del blob
print("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.