Skip to content

Python functools.lru_cache Not Caching Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python functools.lru_cache Not Caching Fix. We cover key concepts, practical examples, and best practices.

Python's functools.lru_cache stores return values of pure functions to avoid recomputation. When caching appears broken, the cause is usually unhashable arguments, mutable default values, or functions with side effects that confuse the cache key.

The Wrong Way

from functools import lru_cache

@lru_cache(maxsize=128)
def get_data(items):
    return sorted(items)

result1 = get_data([3, 1, 2])
result2 = get_data([3, 1, 2])  # Cache miss every time
print(result1)
print(result2)

Output:

[1, 2, 3]
[1, 2, 3]

Each call produces a cache miss because lists are unhashable, so lru_cache cannot store or look up the result.

The Right Way

Use hashable arguments like tuples:

from functools import lru_cache

@lru_cache(maxsize=128)
def get_data(items):
    return sorted(items)

result1 = get_data((3, 1, 2))
result2 = get_data((3, 1, 2))
print(f"Cache info: {get_data.cache_info()}")

Output:

Cache info: CacheInfo(hits=1, misses=1, maxsize=128, currsize=1)

Step-by-Step Fix

1. Use hashable argument types

@lru_cache
def process(items_tuple):
    return sum(items_tuple)

process((1, 2, 3))  # Tuple is hashable

2. Handle unhashable args by converting them

@lru_cache
def fetch_user(user_id, config_frozen):
    config = dict(config_frozen)  # Thaw for use
    return f"User {user_id} with config {config}"

config = frozenset({"theme": "dark", "lang": "en"}.items())
fetch_user(1, config)

3. Remove mutable defaults from cached functions

@lru_cache
def compute(x, cache=None):
    if cache is None:
        cache = {}
    cache[x] = x * x
    return cache

4. Avoid side-effect-dependent functions

import time
from functools import lru_cache

@lru_cache
def expensive(n):
    return n * n

# Functions that depend on time or global state cannot be effectively cached
def time_dependent():
    return int(time.time()) // 60  # Changes every minute

5. Clear the cache when needed

@lru_cache
def get_config(key):
    return f"value_{key}"

get_config("host")
get_config.cache_clear()
get_config("host")  # Cache miss again

Prevention Tips

  • Use hashable types (tuple, str, int, frozenset) as arguments to cached functions.
  • Turn lists into tuples and dicts into frozensets before passing to cached functions.
  • Keep cached functions pure -- no side effects or dependencies on mutable global state.
  • Avoid mutable default arguments in cached functions.
  • Use cache_clear() and cache_info() to monitor and manage caching behavior.

Common Mistakes with functools lru

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. Non-exhaustive pattern matches that compile with warnings then crash at runtime

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### Why does lru_cache require hashable arguments?

lru_cache uses the arguments as dictionary keys in its internal cache. Dictionary keys must be hashable. Lists, dicts, and sets fail because they are mutable and unhashable.

How do I cache a function that takes a list?

Convert the list to a tuple before passing it: process(tuple(my_list)). Alternatively, define a wrapper that converts arguments internally before calling the cached function.

What is the difference between lru_cache and cache?

functools.cache (Python 3.9+) is a simpler, unbounded version of lru_cache with no maxsize limit. Use cache when the number of distinct calls is bounded and known.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro