在functools
pacakge in 中Python3
,有一个lru_cache()
装饰器可以记忆你的函数调用。
有没有办法让我将此缓存转储到文件中,然后稍后将文件加载回内存中?
我在 functools 文档中找不到此功能。实现上述要求的推荐方法是什么,最好使用仅涉及 Python 的解决方案?
在functools
pacakge in 中Python3
,有一个lru_cache()
装饰器可以记忆你的函数调用。
有没有办法让我将此缓存转储到文件中,然后稍后将文件加载回内存中?
我在 functools 文档中找不到此功能。实现上述要求的推荐方法是什么,最好使用仅涉及 Python 的解决方案?
我不知道解决此问题的标准方法。但是你可以这样写你的注释:
def diskcached(cachefile, saveafter=1):
def cacheondisk(fn):
try:
with open(cachefile, 'rb') as f:
cache = pickle.load(f)
except:
cache = {}
unsaved = [0]
@wraps(fn)
def usingcache(*args, **kwargs):
try:
key = hash((args, kwargs))
except TypeError:
key = repr((args, kwargs))
try:
ret = cache[key]
except KeyError:
ret = cache[key] = fn(*args, **kwargs)
unsaved[0] += 1
if unsaved[0] >= saveafter:
with open(cachefile, 'wb') as f:
pickle.dump(cache, f)
unsaved[0] = 0
return ret
return usingcache
return cacheondisk
并与
@diskcached("filename_to_save")
def your_function():
...
这是使用第三方包 joblib ( pip install joblib
) 的不同解决方案,它对我很有帮助:
from joblib import Memory
memory = Memory("/usr/src/app/no_sync/tmp/", verbose=0)
@memory.cache
def args_and_results_of_this_function_are_cached_to_disk(a,b):
return a + b