python的functools lru_cache是否在结果旁边缓存函数参数?



对于以下程序:

from functools import lru_cache

@lru_cache(maxsize=256)
def task_a(a, b):
print(f'Multiplying {a} and {b}')
return a*b

print(task_a(2, 3))
print(task_a(2, 3))
print(task_a(2, 4))
print(task_a(2, 4))
print(task_a(2, 5))
print(task_a(2, 5))

我得到了以下输出:

Multiplying 2 and 3
6
6
Multiplying 2 and 4
8
8
Multiplying 2 and 5
10
10

我的问题是,如果这个装饰器应用于函数,它是使用函数参数还是将函数参数与结果一起缓存?

如果没有,那么当传递相同的参数时,它怎么知道不执行函数呢?

它确实缓存了参数。事实上,参数必须是可散列的,缓存才能工作:

>>> from functools import lru_cache
>>> @lru_cache
... def test(l):
...  pass
...
>>> test([])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

有关更多信息,您可以查看源代码。

最新更新