The*_*ark 5 python functools python-decorators
我想要一个可以使用的函数functools.lru_cache,但默认情况下不能使用。我正在寻找一种使用函数参数的方法,该参数可用于禁用lru_cache. 目前,我有两个版本的功能,一个有lru_cache一个没有。然后我有另一个函数,它用一个参数包装这些函数,该参数可用于控制使用哪个函数
def _no_cache(foo):
print('_no_cache')
return 1
@lru_cache()
def _with_cache(foo):
print('_with_cache')
return 0
def cache(foo, use_cache=False):
if use_cache:
return _with_cache(foo)
return _no_cache(foo)
Run Code Online (Sandbox Code Playgroud)
有没有更简单的方法来做到这一点?
您不能从装饰函数内部禁用缓存。但是,您可以通过直接通过__wrapped__属性访问函数来稍微简化代码。
从文档:
原始底层功能可通过
__wrapped__属性访问。这对于内省、绕过缓存或使用不同的缓存重新包装函数很有用。
演示:
from functools import lru_cache
@lru_cache()
def f(arg):
print(f"called with {arg}")
return arg
def call(arg, use_cache=False):
if use_cache:
return f(arg)
return f.__wrapped__(arg)
call(1)
call(1, True)
call(2, True)
call(1, True)
Run Code Online (Sandbox Code Playgroud)
输出:
called with 1
called with 1
called with 2
Run Code Online (Sandbox Code Playgroud)