Content · Programming · Python

Python functools.cache() Decorator: Usage and Examples

Memoize results without a size limit.

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

Memoize results without a size limit.

What You Will Learn


cache wraps a function in an unbounded lookup cache keyed by hashable arguments. It is equivalent to lru_cache(maxsize=None) and is best for pure functions with a limited input domain.

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 cache
@cache
def square(number):
    print('calculating')
    return number * number
print(square(5))
print(square(5))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: functools.
  • The function square 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:

calculating
25
25

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 cache
@cache
def twice(value):
    return value * 2
print(twice(3), twice(3))
print(twice.cache_info().hits)

Expected output:

6 6
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


Measure cache_info().hits after repeated calls.

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


  • Caching unbounded numbers of distinct arguments can consume memory indefinitely.
  • Using a wrapper without checking which original function, arguments and return values it preserves.

Key Takeaways


  • Memoize results without a size limit.
  • cache wraps a function in an unbounded lookup cache keyed by hashable arguments.
  • 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.