Advertisement
Advanced Python, functools & Functional Programming Tools

How can functools.lru_cache be used with typed=True, and what does that change?

Short answer

By default lru_cache treats arguments that compare equal (like 1 and 1.0) as the same cache key.

Save Python mock interview
Advertisement
AModel answer
By default lru_cache treats arguments that compare equal (like 1 and 1.0) as the same cache key. Setting typed=True makes it cache them separately based on argument type as well as value, which matters when a function's behavior or return type genuinely differs between an int and a float input.
from functools import lru_cache

@lru_cache(maxsize=None, typed=True)
def describe(x):
    return f'{x} is a {type(x).__name__}'

print(describe(1))    # cached separately from...
print(describe(1.0))  # ...this call
Real-world example
A unit-conversion function that behaves differently for int vs float precision inputs uses typed=True so results aren't incorrectly shared across types.
Likely follow-ups
  • What's the performance cost of typed=True?
  • How are unhashable arguments handled by lru_cache?
Related topics