Skip to main content
 首页 » 编程设计

python之lru_cache 转储到文件中并再次加载回内存中

2024年10月24日9lhb25

在 Python3 的 functools 包中,有一个 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(): 
    ...