Last modified: Nov 19, 2026

Python Caching with functools

Python is fast. But some functions are slow. They repeat heavy work again and again. Caching fixes this. It stores results and reuses them.

The functools module gives you simple caching tools. You can add caching with one line of code. No extra libraries are needed.

This guide explains how caching works in Python. It covers lru_cache, cache, and real examples. Beginners will find it easy to follow.

What Is Caching?

Caching means saving the result of a function. When the same input comes back, Python returns the saved result. The function does not run again.

This saves time. It also saves memory and CPU. Caching works best with pure functions. A pure function returns the same output for the same input.

Think of a Fibonacci function. It recalculates the same numbers many times. Caching stops that waste.

Why Use functools for Caching?

The functools module is part of the standard library. It is always available. It needs no installation.

It gives you ready-made decorators. You do not write cache logic yourself. You just wrap your function.

This keeps your code clean and readable. It also avoids common bugs in hand-written caches.

The lru_cache Decorator

lru_cache is the most popular caching tool in Python. LRU means Least Recently Used. When the cache is full, the least used result is removed.

Here is a simple example:


from functools import lru_cache

@lru_cache(maxsize=None)
def square(n):
    print(f"Calculating square of {n}")
    return n * n

print(square(4))
print(square(4))
print(square(5))

Calculating square of 4
16
16
Calculating square of 5
25

Notice the second call to square(4). It did not print "Calculating". The result came from the cache.

The maxsize argument sets the cache size. maxsize=None means unlimited size. You can also set a number, like maxsize=128.

If you want to go deeper into this decorator, read this guide on Python Functools: lru_cache and partial.

Caching Recursive Functions

Recursion is a great fit for caching. Recursive functions often repeat the same calls. Caching turns slow recursion into fast code.

Here is a Fibonacci example:


from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)  # results are cached

print(fib(30))

832040

Without caching, fib(30) would make millions of calls. With caching, it makes only about 30. That is a huge speed gain.

If recursion still feels tricky, this article on Python Recursion Explained with Examples will help.

Using the cache Decorator

Python 3.9 added a simpler decorator. cache is a short form of lru_cache(maxsize=None).

Use it when you want an unlimited cache and simple code.


from functools import cache

@cache
def add(a, b):
    print("Running add")
    return a + b

print(add(2, 3))
print(add(2, 3))

Running add
5
5

The function ran only once. The second call used the stored result.

Checking Cache Stats

You can see how well your cache works. Call cache_info on the wrapped function.


from functools import lru_cache

@lru_cache(maxsize=2)
def double(n):
    return n * 2

double(1)
double(2)
double(3)  # cache is full, oldest entry removed
print(double.cache_info())

CacheInfo(hits=0, misses=3, maxsize=2, currsize=2)

Hits are cache uses. Misses are real function runs. This data helps you tune maxsize.

You can also clear the cache with cache_clear. This is useful in tests or long-running apps.

Important Rules and Caveats

Caching is powerful. But it has rules. Follow them to avoid bugs.

Arguments must be hashable. Lists and dicts cannot be cached directly. Use tuples instead.

Do not cache functions with side effects. If a function writes files or calls APIs, caching may return stale data.

Watch memory use. An unlimited cache can grow forever. Set maxsize for long-running programs.

Results are shared. Cached objects are the same object. If you mutate a returned list, you mutate the cache. This links to the idea in Python id Function and Object Identity, where identity matters.

Caching Methods in Classes

You can cache methods too. But there is a catch. self becomes part of the cache key.

That means each instance has its own cache entries. This can leak memory if you create many objects.

For classes, consider caching at the class level or using a custom cache. Keep an eye on object lifetime and memory.

When Not to Use Caching

Do not cache everything. Caching adds overhead. For cheap functions, the overhead can be slower than the function itself.

Do not cache functions that depend on time, random values, or external state. The result will be wrong.

Profile first. Use cache_info to check real gains. Optimize what is slow, not what looks slow.

Conclusion

Python caching with functools is simple and effective. The lru_cache decorator adds caching in one line. The cache decorator is even shorter.

Use caching for pure, slow, repeated functions. Check stats with cache_info. Set a sensible maxsize.

Follow these rules, and your Python code will run faster with less effort.