General problem: How can I access a variable in a function's closure?
Specific problem: How can I access the raw cache
from a python function wrapped with functools.lru_cache()
?
If I memoize a function (example taken from the docs)...
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
>>> [fib(n) for n in range(16)]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
>>> fib.cache_info()
CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
Here is where cache
is defined: https://github.com/python/cpython/blob/f0851910eb8e711bf8f22165cb0df33bb27b09d6/Lib/functools.py#L491
When fib()
is memoized, lru_cache
adds a cache_info()
and cache_clear()
function to the wrapper. cache_clear()
has access to cache
and I have access to cache_clear()
so can I somehow use that to access cache
directly?
You can use cachier
by Shay Palachy. You can tell it to cache to a pickle file.
Alternatively, look at persistent_lru_cache
developed by Andrew Barnert.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With