Weak References
Applications
- Caching of previously computed results
import weakref
def foo(x,cache={}):
wr = cache.get(x,None)
if wr == None or wr() == None:
r = compute_foo(x) # Compute result
cache[x] = weakref.ref(r) # Create weak reference to it
return r
else:
return wr() # Return previous result
- Weak reference allows original object to go away when no longer in use.
Caveats
- Weak references only work with instances, functions, and methods.
- Weak references to strings, lists, dictionaries, etc. not currently supported.
|