加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 用于选择性缓存/ memoization的装饰器

发布时间:2020-12-20 11:40:26 所属栏目:Python 来源:网络整理
导读:我正在寻找一种构建装饰器@memoize的方法,我可以在函数中使用如下: @memoizemy_function(a,b,c): # Do stuff # result may not always be the same for fixed (a,c)return result 然后,如果我这样做: result1 = my_function(a=1,b=2,c=3)# The function f
我正在寻找一种构建装饰器@memoize的方法,我可以在函数中使用如下:

@memoize
my_function(a,b,c):
    # Do stuff 
    # result may not always be the same for fixed (a,c)
return result

然后,如果我这样做:

result1 = my_function(a=1,b=2,c=3)
# The function f runs (slow). We cache the result for later

result2 = my_function(a=1,c=3)
# The decorator reads the cache and returns the result (fast)

现在说我要强制缓存更新:

result3 = my_function(a=1,c=3,force_update=True)
# The function runs *again* for values a,and c. 

result4 = my_function(a=1,c=3)
# We read the cache

在上面的结尾,我们总是有result4 = result3,但不一定是result4 = result,这就是为什么需要一个选项来强制相同输入参数的缓存更新.

我该如何处理这个问题?

关于joblib的注意事项

据我所知joblib支持.call,它强制重新运行,但它是does not update the cache.

关于使用klepto的后续行动:

有没有办法让klepto(参见@ Wally的答案)默认在特定位置缓存其结果? (例如/ some / path /)并在多个函数之间共享此位置?例如.我想说

cache_path = "/some/path/"

然后在同一路径下@memoize给定模块中的几个函数.

解决方法

我建议看看joblib和klepto.两者都有非常可配置的缓存算法,可以做你想要的.

两者都可以为result1和result2进行缓存,而klepto提供对缓存的访问,因此可以从本地内存缓存中弹出结果(不将其从存储的存档中删除,比如在数据库中).

>>> import klepto
>>> from klepto import lru_cache as memoize
>>> from klepto.keymaps import hashmap
>>> hasher = hashmap(algorithm='md5')
>>> @memoize(keymap=hasher)
... def squared(x):
...   print("called")
...   return x**2
... 
>>> squared(1)
called
1
>>> squared(2)
called
4
>>> squared(3)
called
9
>>> squared(2)
4
>>> 
>>> cache = squared.__cache__()
>>> # delete the 'key' for x=2
>>> cache.pop(squared.key(2))
4
>>> squared(2)
called
4

不完全是您正在寻找的关键字界面,但它具有您正在寻找的功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读