Accessing the lru_cache cache
A common problem . How can I access the variable when the function is closed?
Specific problem . How can I access raw cache
from a python function wrapped in 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)
It is defined here cache
: https://github.com/python/cpython/blob/f0851910eb8e711bf8f22165cb0df33bb27b09d6/Lib/functools.py#L491
When fib()
remembered, it lru_cache
adds cache_info()
and functions to the wrapper cache_clear()
. cache_clear()
has access to cache
, and I have access to cache_clear()
, so can I somehow use this to directly access cache
?
source to share
You can use Shay Palachy . You can tell that it caches the pickle file .cachier
Alternatively, take a look persistent_lru_cache
, designed by Andrew Barnert .
source to share