我用我在工作中遇到的一些代码编写了这个简单、人为的示例。我试图更好地理解为什么 slow_function_1 (+ 其装饰器的结构方式)会正确缓存函数结果,但应用于 slow_function_2 的装饰器不会。在这个例子中,我试图在调用方法后访问缓存信息;但是,我一直收到以下错误:AttributeError: 'function' object has no attribute 'cache_info'. 我一直在寻找高低试图解决这个问题,但无济于事。此 AttributeError 为slow_function_1.cache_info()和slow_function_2.cache_info()
如何查看函数调用之间的缓存?如果有人对为什么 slow_function_1 和 slow_function_2 缓存行为不同的原始问题有任何见解,我也将不胜感激。
先感谢您!
import functools
import time
def format_args(func):
def inner(*args, **kwargs):
formatted_args = [tuple(x) if type(x) == list else x for x in args]
return func(*formatted_args, **kwargs)
return inner
def formatted_cache(func):
def inner(*args, **kwargs):
formatted_args = [tuple(x) if type(x) == list else x for x in args]
return functools.lru_cache()(func)(*formatted_args, **kwargs)
return inner
@format_args
@functools.lru_cache
def slow_function_1(a: list, b: bool):
time.sleep(1)
print("executing slow function 1")
return sum(a)
@formatted_cache
def slow_function_2(a: list, b: bool):
time.sleep(1)
print("executing slow function 2")
return functools.reduce((lambda x, y: x*y), a)
example_list = [1,2,3,4,5,6,7,8,9,10,11,12]
example_bool = True
slow_function_1(example_list, example_bool)
print(slow_function_1.cache_info())
slow_function_1(example_list, example_bool)
print(slow_function_1.cache_info())
slow_function_2(example_list, example_bool)
print(slow_function_2.cache_info())
slow_function_2(example_list, example_bool)
print(slow_function_2.cache_info())