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

python – 用于选择性缓存 memoization的装饰器,第1张

概述我正在寻找一种构建装饰器@memoize的方法,我可以在函数中使用如下: @memoizemy_function(a, b, c): # Do stuff # result may not always be the same for fixed (a,b,c)return result 然后,如果我这样做: result1 = my_function(a=1,b=2,c=3 我正在寻找一种构建装饰器@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 runs (slow). We cache the result for laterresult2 = 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提供对缓存的访问,因此可以从本地内存缓存中d出结果(不将其从存储的存档中删除,比如在数据库中).

>>> 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)called1>>> squared(2)called4>>> squared(3)called9>>> squared(2)4>>> >>> cache = squared.__cache__()>>> # delete the 'key' for x=2>>> cache.pop(squared.key(2))4>>> squared(2)called4

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

总结

以上是内存溢出为你收集整理的python – 用于选择性缓存/ memoization的装饰器全部内容,希望文章能够帮你解决python – 用于选择性缓存/ memoization的装饰器所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1193291.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存