Skip to content
Python Basics: Reusing Results with functools

Python Basics: Reusing Results with functools

October 12, 2026

A script may repeat the same calculation many times. A small cache can reuse earlier results. Python’s standard-library functools module provides lru_cache() for this job.

Use Python 3.12 or newer in Bash on Linux. These independent examples use sample values in memory.

Reuse a previous calculation

Save as demo_functools_1.py:

from functools import lru_cache

@lru_cache(maxsize=2)
def square(number):
    print("Calculating:", number)
    return number * number

print("Result:", square(4))
print("Result:", square(4))
print(square.cache_info())

Run it from the directory where you saved it:

python3 demo_functools_1.py

Output:

Calculating: 4
Result: 16
Result: 16
CacheInfo(hits=1, misses=1, maxsize=2, currsize=1)

The decorator checks saved arguments before running the function. The diagnostic print makes the skipped work visible; do not cache a function whose side effects must happen on every call. A hit reuses a result; a miss runs the calculation.

Bound and clear the cache

Save as demo_functools_2.py:

from functools import lru_cache

@lru_cache(maxsize=2)
def square(number):
    return number * number

for number in (1, 2, 1, 3):
    square(number)
print(square.cache_info())
square(2)
print(square.cache_info())
square.cache_clear()
print(square.cache_info())

Run it from the directory where you saved it:

python3 demo_functools_2.py

Output:

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

Adding 3 evicts 2, the least recently used entry. The limit counts entries, not bytes. Arguments and results stay referenced while cached. cache_clear() removes entries and resets counters. There is no automatic time-based expiry.

Use hashable arguments

Save as demo_functools_3.py:

from functools import lru_cache

@lru_cache(maxsize=16)
def total(values):
    return sum(values)

print("Tuple:", total((2, 3, 5)))
try:
    total([2, 3, 5])
except TypeError:
    print("A list cannot be a cache key")
print("Empty tuple:", total(()))

Run it from the directory where you saved it:

python3 demo_functools_3.py

Output:

Tuple: 10
A list cannot be a cache key
Empty tuple: 0

Tuples work here because their elements are hashable too. Prefer functions whose result depends only on their arguments. Changing files or global settings can make a saved result stale. Avoid mutable return values: callers receive the cached object itself.

References

Acknowledgements

This post was created with assistance from AI.

Last updated on