0
0
PythonHow-ToBeginner · 3 min read

How to Use LRU Cache in Python: Simple Guide with Examples

Use functools.lru_cache decorator to cache function results and speed up repeated calls with the same arguments. Simply add @lru_cache(maxsize=128) above your function to enable caching with a limit on stored results.
📐

Syntax

The lru_cache decorator is used to wrap a function to cache its return values. It accepts an optional maxsize parameter to limit the number of cached results. When the cache is full, the least recently used items are discarded.

  • @lru_cache(maxsize=128): Decorates the function to cache up to 128 results.
  • maxsize=None: Cache unlimited results (use with caution).
  • The decorated function must have hashable arguments.
python
from functools import lru_cache

@lru_cache(maxsize=128)
def my_function(args):
    # function body
    pass
💻

Example

This example shows how to use lru_cache to speed up a recursive Fibonacci function by caching previously computed values.

python
from functools import lru_cache

@lru_cache(maxsize=100)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(10))
Output
55
⚠️

Common Pitfalls

Common mistakes when using lru_cache include:

  • Using unhashable arguments like lists or dictionaries, which causes errors.
  • Not considering cache size, which can lead to high memory use if maxsize is too large or None.
  • Expecting cache to work across different program runs (it only caches during runtime).
python
from functools import lru_cache

# Wrong: list argument is unhashable
@lru_cache(maxsize=32)
def sum_list(numbers):
    return sum(numbers)

# Right: convert list to tuple (which is hashable)
@lru_cache(maxsize=32)
def sum_tuple(numbers):
    return sum(numbers)
📊

Quick Reference

Summary tips for using lru_cache:

  • Use @lru_cache(maxsize=128) to cache function results automatically.
  • Ensure function arguments are hashable (e.g., tuples, strings, numbers).
  • Use cache_clear() method to reset the cache if needed.
  • Check cache info with cache_info() to monitor hits and misses.

Key Takeaways

Use @lru_cache decorator to cache function results and improve performance.
Set maxsize to limit cache size and avoid excessive memory use.
Function arguments must be hashable for caching to work.
Use cache_clear() to reset the cache when needed.
Check cache_info() to understand cache effectiveness.