Last modified: Nov 19, 2026

Python Functools: lru_cache and partial

The functools module ships with Python. It holds small tools that solve common problems. Two of its stars are lru_cache and partial.

These tools look simple. Yet they save real time and real lines of code. This article explains both with clear examples.

What Is the functools Module?

functools is part of the Python standard library. You do not install anything. Just import what you need.

It offers helpers for working with functions. You can cache results, freeze arguments, and build wrappers. It pairs well with other functional tools like the ones in our guide on Python lambda vs function differences.

Let's start with caching.

Why Caching Matters

Some functions are expensive. They loop many times or call slow resources. If the same inputs return the same output, why compute twice?

Caching stores results. The next call with the same arguments returns the stored value. This turns slow work into a fast lookup.

Meet lru_cache

lru_cache is a decorator. It wraps your function with a cache. LRU means "least recently used." When the cache is full, the oldest unused entry is dropped.

It works best on pure functions. Same input must always give the same output. It also needs hashable arguments, like numbers, strings, or tuples.

Basic lru_cache Example


from functools import lru_cache

@lru_cache(maxsize=None)  # None means unlimited cache size
def slow_square(n):
    print(f"Computing square of {n}")
    return n * n

print(slow_square(4))
print(slow_square(4))  # This call uses the cache
print(slow_square(5))

Computing square of 4
16
16
Computing square of 5
25

Notice the print statement. It runs only once for 4. The second call returns the cached value instantly.

Setting maxsize

The maxsize argument controls how many results are kept. Use a number to cap memory. Use None for no limit.

A small maxsize is safer for long-running programs. It prevents the cache from growing forever.

Real Speed Gain: Fibonacci

Recursive code is a classic caching win. Without a cache, Fibonacci numbers explode in cost. With lru_cache, each number is computed once.


from functools import lru_cache

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)  # Each value cached after first compute

print(fib(30))
print(fib.cache_info())  # Inspect cache hits and misses

832040
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)

The cache_info method shows hits and misses. Hits mean the cache saved work. Misses mean a fresh computation happened.

You can wipe the cache with cache_clear. This is handy in tests or long sessions.

If you enjoy recursion tricks, our guide on Python recursion explained with examples is a good next read.

When Not to Use lru_cache

Skip lru_cache when results change over time. File reads and network calls often return new data. Caching them can serve stale values.

Also avoid it with unhashable arguments. Lists and dicts will raise a TypeError.


from functools import lru_cache

@lru_cache(maxsize=10)
def total(items):
    return sum(items)

total([1, 2, 3])  # Lists are unhashable, so this fails

TypeError: unhashable type: 'list'

The fix is simple. Pass a tuple instead of a list. Tuples are hashable and safe for caching.

Meet partial

partial creates a new function with some arguments locked in. Think of it as a pre-filled form. You supply the blanks once and reuse them.

This removes repetition. It also makes callbacks and sorting cleaner.

Basic partial Example


from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)  # Lock exponent to 2
cube = partial(power, exponent=3)    # Lock exponent to 3

print(square(5))
print(cube(2))

25
8

We built two new functions from one. No lambdas, no extra defs. The intent stays clear.

partial in Sorting

Sorting with a custom key is a common use. partial lets you reuse a key function with fixed settings.


from functools import partial

def sort_key(text, reverse_weight):
    return text.lower() * reverse_weight

words = ["Banana", "apple", "Cherry"]
key = partial(sort_key, reverse_weight=1)

print(sorted(words, key=key))

['apple', 'Banana', 'Cherry']

You can also pair partial with built-ins. For example, fix the base in int to parse binary strings.


from functools import partial

parse_binary = partial(int, base=2)  # Always parse base 2
print(parse_binary("1010"))

10

partial vs Lambda

Many people use lambdas for this job. Both work. But partial is often cleaner.

It is self-documenting. It also plays well with tools like inspect. If you are unsure which fits, read our comparison of Python lambda vs function key differences.

Using Both Together

The two tools combine well. You can cache a function that was built with partial. Or you can freeze arguments before caching.


from functools import lru_cache, partial

def area(length, width):
    print("Calculating area")
    return length * width

fixed_width = partial(area, width=10)  # Width always 10
cached_area = lru_cache(maxsize=100)(fixed_width)

print(cached_area(3))
print(cached_area(3))  # Cached, no print

Calculating area
30
30

The first call computes. The second call hits the cache. This pattern shines in data pipelines with repeated shapes.

Common Mistakes to Avoid

First, do not cache functions with side effects. Logging and printing are fine, but database writes are not.

Second, watch memory. An unlimited cache on a hot function can grow large. Set a sensible maxsize.

Third, remember that partial keeps keyword arguments overridden at call time. If you pass the same keyword again, your call value wins.

Fourth, cached functions keep references to arguments. This can delay garbage collection for big objects.

Quick Reference

Use lru_cache for repeat calls with the same hashable inputs. It is a one-line speed boost.

Use partial to remove repeated arguments. It builds small, readable helper functions.

Both live in functools, so the import cost is zero. Both work with normal functions and methods.

If you use methods, remember how attribute lookup works. Our guide on the Python property decorator explained covers related class patterns.

Conclusion

lru_cache and partial are small tools with big returns. Caching cuts wasted work. Partial application cuts wasted typing.

Start with lru_cache on one slow pure function. Then try partial on a repeated call. Measure the change and keep what helps.

Keep functions simple and readable. Let functools handle the repetition. Your code will be faster and easier to maintain.