【问题标题】:lru_cache dump into a file and loading back into in-memory againlru_cache 转储到文件中并再次加载回内存中
【发布时间】:2016-06-15 00:50:51
【问题描述】:

在Python3 中的functools pacakge 中,有一个lru_cache() 装饰器,它将记忆您的函数调用。

有没有办法让我将此缓存转储到文件中,然后再将文件加载回内存中?

我在 functools 文档中找不到此功能。实现上述要求的推荐方法是什么,最好使用仅涉及 Python 的解决方案?

【问题讨论】:

标签: python python-3.x caching in-memory-database functools


【解决方案1】:

我不知道解决此问题的标准方法。 但是你可以这样写你的注释:

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():
    ...

【讨论】:

    【解决方案2】:

    这是一个使用第三方包 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
    

    【讨论】:

      猜你喜欢
      • 2014-06-21
      • 2020-07-04
      • 2014-11-13
      • 2014-04-06
      • 2012-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      相关资源
      最近更新 更多