Does python's functools lru_cache caches function parameters alongside the result?

835 Views Asked by At

For the following program:

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))

I got the following output:

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

My question is, if this decorator is applied on the function, does it make use of function parameters or does it caches the function parameters along with the result?

If no, then how does it know not to execute the function when same parameters are passed?

1

There are 1 best solutions below

2
Bharel On

It does cache the parameters. In fact, the parameters must be hashable for the cache to work:

>>> 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'

For more info, you can take a look at the source code.