Content · Programming · Python

Python functools.lru_cache() Decorator: Usage and Examples

Cache recent function results with a maximum entry count.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Cache recent function results with a maximum entry count.

What You Will Learn


lru_cache(maxsize=...) evicts least-recently-used entries. Arguments must be hashable; typed=True distinguishes some argument types for cache keys.

Caching uses extra memory and can return stale results when a function relies on changing state outside its arguments.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from functools import lru_cache
@lru_cache(maxsize=2)
def calculate_total(amount):
    return amount * 1.2
print(calculate_total(10))
print(calculate_total(10))
print(calculate_total.cache_info())

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: functools.
  • The function calculate_total defines reusable behavior; its body executes when it is called, not when it is declared.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

12.0
12.0
CacheInfo(hits=1, misses=1, maxsize=2, currsize=1)

Another Example: Compare the Results


Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.

from functools import lru_cache
@lru_cache(maxsize=2)
def cube(value):
    return value ** 3
print(cube(2), cube(2))
print(cube.cache_info().hits)

Expected output:

8 8
1

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Set maxsize=2 and inspect cache misses after visiting three unique inputs.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Decorating functions that depend on time or mutable external state and assuming cached results are always fresh.
  • Overlooking this documented constraint: arguments must be hashable; typed=True distinguishes some argument types for cache keys.

Key Takeaways


  • Cache recent function results with a maximum entry count.
  • lru_cache(maxsize=...) evicts least-recently-used entries.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.