如何在python @ functools.lru_cache上使用cache_clear()

cjm*_*671 38 python python-3.x

文件说明:

装饰器还提供cache_clear()清除或使缓存无效的功能.

它没有提供有关如何使用的任何示例或指导 cache_clear()

我有两个问题:

  • 如何cache_clear()从不同的功能运行?
  • 如果我cache_clear()有条件地将一个调用放在正在缓存的函数中,它会被执行吗?

mat*_*ino 63

除了缓存,lru_cache装饰器还为装饰功能添加了新功能 - cache_info和cache_clear.下面是一个简单的例子,可以解释它们是如何工作的:

>>> @lru_cache(5)
... def foo():
...     print('Executing foo...')
... 
>>> foo()
Executing foo...
>>> foo()
>>> foo.cache_info()
CacheInfo(hits=1, misses=1, maxsize=5, currsize=1)
>>> foo.cache_clear()
>>> foo()
Executing foo...
Run Code Online (Sandbox Code Playgroud)

回答你的问题:

如果我有条件地将cache_clear()调用放在正在缓存的函数中,它会被执行吗?

如果结果尚未缓存,则函数将执行并根据您的条件执行cache_clear.我不会,虽然使用这样的解决方案-一个很好的做法是将缓存的对象之外无效,否则你在最坏的情况下,在所有的风险没有失效,在最好的情况下不可读的代码.

如何从不同的函数运行cache_clear()?

只需导入缓存函数并调用cache_clear它:

from x import foo

def bar():
    foo.cache_clear()
Run Code Online (Sandbox Code Playgroud)


Alo*_*man 8

如果您尝试使缓存过期的方法是一个属性:

class Foo:
    @property
    @lru_cache()
    def bar(self):
       return 42
Run Code Online (Sandbox Code Playgroud)

然后你可以通过这种方式清除缓存:

Foo.bar.fget.cache_clear()
Run Code Online (Sandbox Code Playgroud)

看到这个答案:https : //stackoverflow.com/a/55497384/8953378