Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. functools.lru_cache() / functools.wraps()

functools.lru_cache() / functools.wraps()

functools.lru_cache() is a decorator that caches the return value of a function so that repeated calls with the same arguments return the cached result without recomputation (memoization). functools.wraps() is a decorator used when writing decorators to preserve the original function's metadata (name, docstring, etc.). Using lru_cache can greatly speed up recursive computations and other processes that repeatedly perform the same calculation.

Syntax

from functools import lru_cache, cache, wraps

# LRU cache with a maximum size
@lru_cache(maxsize=128)
def func(args):
    ...

# Unlimited cache (Python 3.9+)
@cache
def func(args):
    ...

# Preserving metadata when writing a decorator
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        ...
    return wrapper

Functions and Attributes

Function / AttributeDescription
lru_cache(maxsize=128)A decorator that caches results using the LRU strategy. Set maxsize=None for an unlimited cache.
cache()Equivalent to lru_cache(maxsize=None). Available in Python 3.9 and later.
func.cache_info()Returns the number of hits, misses, maximum size, and current size of the cache.
func.cache_clear()Clears all entries from the cache.
wraps(func)Copies the metadata from the original func onto the wrapper function inside a decorator.

Sample Code

from functools import lru_cache, cache, wraps
import time

# lru_cache: speed up Fibonacci computation
@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(50))          # 12586269025 (computed instantly)
print(fib.cache_info()) # CacheInfo(hits=48, misses=51, maxsize=None, currsize=51)

# Clear the cache
fib.cache_clear()

# lru_cache: LRU cache with a fixed maxsize
@lru_cache(maxsize=4)
def slow_func(n):
    time.sleep(0.1)     # simulate a slow operation
    return n * n

# cache (Python 3.9+): shorthand for an unlimited cache
@cache
def expensive(x, y):
    return x ** y

# wraps: preserve metadata when writing a decorator
def timer(func):
    @wraps(func)        # without this, __name__ would be 'wrapper'
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        print(f"{func.__name__} took {time.time() - start:.4f}s")
        return result
    return wrapper

@timer
def greet(name):
    """Returns a greeting message."""
    return f"Hello, {name}!"

print(greet('Alice'))   # Hello, Alice! + elapsed time
print(greet.__name__)   # 'greet' (would be 'wrapper' without wraps)
print(greet.__doc__)    # 'Returns a greeting message.'

Notes

The LRU in lru_cache() stands for Least Recently Used. When the cache reaches its maxsize limit, the least recently used entry is evicted to make room for a new one. Arguments passed to a cached function must be hashable, so lists and dictionaries cannot be used as arguments. Use immutable types such as tuples, strings, or numbers, or convert arguments to tuples before passing them.

wraps() is a best practice for implementing decorators correctly. Without it, the decorated function's __name__ and __doc__ attributes are replaced by those of the inner wrapper function, which can cause problems during debugging and documentation generation.

If you find any errors or copyright issues, please .