What do functools.lru_cache, partial, and wraps each do?medium

Type
conceptual
Topic
functools-wraps
Frequency
common
Tags
functools, lru_cache, partial, memoization, decorators
Answer

lru_cache memoizes function results — on repeated calls with the same args it returns the cached result immediately. partial pre-fills some arguments to create a new callable. wraps preserves the wrapped function's __name__ and __doc__ inside a decorator.

Explanation

@lru_cache(maxsize=128) stores the last N results keyed by arguments (which must be hashable). Use maxsize=None or @cache (Python 3.9+) for unlimited caching — critical for expensive embedding lookups or repeated tokenization. partial(fn, *args, **kwargs) creates a new callable with some arguments pre-filled, useful for configuring callbacks without lambda. @functools.wraps(fn) inside a decorator copies __name__, __doc__, and other attributes so the wrapper appears as the original in stack traces and help().

Follow-upWhat happens if you pass a list (unhashable) to a function decorated with @lru_cache?
Follow-upHow is functools.partial different from a lambda?
Follow-upWhy do you need @functools.wraps in a decorator?