0

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?

sj95126
  • 6,520
  • 2
  • 15
  • 34
Deepak Tatyaji Ahire
  • 4,883
  • 2
  • 13
  • 35
  • 2
    What is not answered by the [official documentation](https://docs.python.org/3/library/functools.html#functools.lru_cache)? `Distinct argument patterns may be considered to be distinct calls with separate cache entries. For example, f(a=1, b=2) and f(b=2, a=1) differ in their keyword argument order and may have two separate cache entries.` – dantiston Aug 23 '22 at 14:28

1 Answers1

0

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.

Bharel
  • 23,672
  • 5
  • 40
  • 80
  • Hey thanks for answer. But the question remains the same -> "then how does it know not to execute the function when same parameters are passed?" – Deepak Tatyaji Ahire Aug 23 '22 at 13:27
  • 1
    @DeepakTatyajiAhire You said "if no..." but it does cache the parameters... You simply look up for the parameters in a dictionary. – Bharel Aug 23 '22 at 13:29