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

我正在寻找一种构建装饰器@memoize的方法,我可以在函数中使用如下:

@memoize
my_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)
# The function f runs (slow). We cache the result for later

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

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

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

result4 = my_function(a=1, b=2, 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

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

点赞