问题描述
文档指出:
装饰器还提供了一个 cache_clear()
函数用于清除或使缓存无效.
它没有提供关于如何使用 cache_clear()
我有两个问题:
- 如何从不同的函数运行
cache_clear()
? - 如果我有条件地将
cache_clear()
调用放入正在缓存的函数中,它会被执行吗?
除了缓存之外,lru_cache
装饰器还添加了新的函数,对被装饰的函数 - cache_info
和 >cache_clear
.下面是一个简单的例子,可以解释它们是如何工作的:
回答您的问题:
如果我在被缓存的函数中有条件地调用 cache_clear() ,它会被执行吗?
如果结果尚未缓存,该函数将执行并根据您的条件执行cache_clear
.不过我不会使用这样的解决方案 - 一个好的做法是在缓存对象之外无效,否则在最坏的情况下你根本不会有无效的风险,在最好的情况下是不可读的代码.
如何从不同的函数运行 cache_clear()?
只需导入缓存函数并调用 cache_clear
即可:
from x import foo定义栏():foo.cache_clear()
The documentation states:
It doesn't provide any examples or guidance on how to use cache_clear()
I have two questions:
- How can I run
cache_clear()
from a different function? - If I put a
cache_clear()
call conditionally inside the function that is being cached, will it ever get executed?
Besides caching, lru_cache
decorator also adds new functions, to the decorated function - cache_info
and cache_clear
. Below is a simple example that should explain how they work:
>>> @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...
Answering your questions:
If the result is not cached already, the function will execute and based on your conditions, it should execute cache_clear
. I wouldn't use such solution though - a good practise is to invalidate outside the cached object, otherwise you risk no invalidation at all in worst cases, unreadable code in best case.
Just import cached function and call cache_clear
on it:
from x import foo
def bar():
foo.cache_clear()
这篇关于我如何在 python @functools.lru_cache 上使用 cache_clear()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!