【发布时间】:2015-04-03 08:53:47
【问题描述】:
我正在寻找一种构建装饰器@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 同一路径下给定模块中的几个函数。
【问题讨论】:
-
functools.lru_cache是一个 memoization 装饰器,它提供了一种清除整个缓存的方法(但不是像您的示例中那样的特定调用)。
标签: python memoization python-decorators joblib klepto