functools — higher-order functions and caching

Python functools.lru_cache and cache, including hashable arguments and cached side effects, plus partial and wraps.

模块页正文目前为英文。

The functools module is part of the Python standard library. It is not a third-party package. Import it with `import functools`. The caching decorators remember return values by argument. They do not run the function body again on a cache hit, so any side effect inside the function also happens only on a miss.

Cache keys must be hashable. Lists, dicts, and other mutable containers cannot be used as arguments unless you convert them to a hashable form first. This page covers lru_cache, cache, partial, and wraps. It does not cover every helper in the module.

Examples were checked against Python 3.13. See the official documentation for the complete API.

Python reference overview →

lru_cache and cache

lru_cache(maxsize=128, typed=False) stores up to maxsize recent calls. cache(), added in Python 3.9, is equivalent to lru_cache(maxsize=None): the cache is unbounded. On a hit, the stored return value is reused and the function body is skipped.

A TypeError is raised when an argument is unhashable. That happens at the call, not at decoration time. cache_info() reports hits, misses, maxsize, and currsize. cache_clear() empties the cache.

functools.lru_cache, functools.cache

functools.lru_cache(maxsize=128, typed=False)
functools.cache(user_function)

Memoize a function by hashable arguments. A cache hit returns the stored result and does not run the function body again, so side effects are also cached.

ParameterDescription
maxsizeThe maximum number of distinct calls to keep. None disables eviction. cache() is the unbounded form.
typedIf True, values of different types are stored separately, so 3 and 3.0 are distinct keys.

Returns: A wrapped function. The wrapper has cache_info() and cache_clear() methods. cache_info() returns a named tuple of hits, misses, maxsize, and currsize.

Raises

  • TypeError — Raised when an argument is unhashable, for example a list or a dict. The message is typically "unhashable type: 'list'".
  • In the example, add(1, 2) is called twice in the printed sequence but appears only once in the side-effect log, because the second call is a cache hit.
  • Do not cache a function whose result depends on global state, time, or I/O unless you are prepared for stale values.
python
from functools import cache, lru_cache

calls = []

@lru_cache(maxsize=2)
def add(a, b):
    calls.append((a, b))
    return a + b

print(add(1, 2), add(1, 2), add(2, 3), add(1, 2))
print(calls)
print(add.cache_info())

try:
    add([1], 2)
except TypeError as exc:
    print(f"{type(exc).__name__}: {exc}")

side = []

@cache
def bump(n):
    side.append(n)
    return n + 1

print(bump(1), bump(1), side)

Expected output

3 3 5 3
[(1, 2), (2, 3)]
CacheInfo(hits=2, misses=2, maxsize=2, currsize=2)
TypeError: unhashable type: 'list'
2 2 [1]

Official documentation →

partial and wraps

partial(func, /, *args, **keywords) returns a new callable with some arguments already filled in. wraps(original) is a decorator for wrapper functions; it copies the original name, docstring, and other metadata so tools and tracebacks still describe the wrapped function.

functools.partial, functools.wraps

functools.partial(func, /, *args, **keywords)
functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)

Bind arguments ahead of time, or copy a wrapped function's metadata onto a decorator wrapper.

ParameterDescription
func / wrappedThe function to bind or to copy metadata from.
args, keywordsValues supplied in advance by partial. Later calls can add the remaining positional arguments and override keywords.

Returns: partial returns a new callable. wraps returns a decorator that updates the wrapper in place and returns it.

  • Without wraps, a decorator typically exposes the wrapper's name, such as "wrapper", instead of the original function name.
python
from functools import partial, wraps

def greet(name, punct="!"):
    return f"hello {name}{punct}"

hi = partial(greet, punct="?")
print(hi("Ada"))

def deco(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

@deco
def original():
    """doc"""
    return 1

print(original.__name__, original.__doc__)

Expected output

hello Ada?
original doc

Official documentation →