Monday, 8 November 2021

Treat distinct argument patterns while using lru_cache decorator as the same calls

As mentioned in the official documentation, Python's functools.lru_cache decorator interprets distinct args patterns as completely different cache keys. For example:

import functools

@functools.lru_cache(maxsize=128)
def test(a, b, *, c, d):
    print(f'Hello from function: ({a}, {b}, {c}, {d})')

test(1, 2, c=42, d='answer')
test(1, 2, d='answer', c=42)
test(b=2, a=1, c=42, d='answer')

While effectively all function calls are the same, the code above produces the following output:

Hello from function: (1, 2, 42, answer)
Hello from function: (1, 2, 42, answer)
Hello from function: (1, 2, 42, answer)

What is the more "pythonic" way to overcome that to treat such kinds of calls as the same?



from Treat distinct argument patterns while using lru_cache decorator as the same calls

No comments:

Post a Comment