Python functools — partial, lru_cache, reduce, and wraps
Some code repeats the same call shape over and over: the same function with one argument already known, the same costly result computed again, a wrapper that loses the name of the function it wraps. The functools module fixes those shapes. This guide fixes arguments with partial, caches results with lru_cache and cache, folds values with reduce, keeps a wrapper honest with wraps, and ends with total_ordering and singledispatch.
Written November 13, 2026 · Tested with Python 3.12.3 · 4 min read
- The main program: fixing an argument with partial
- Fixing words and overriding at call time
- Remembering results: lrucache
- The short form: cache, and the typed switch
Written November 13, 2026
Tested with Python 3.12.3
What this guide is
The functools module holds tools for working with functions themselves: building a new callable from an old one, caching its results, and copying its identity onto a wrapper. The workhorses are partial, which fixes arguments in advance, lru_cache and cache, which remember results, reduce, which folds a sequence down to one value, and wraps, which a decorator uses to keep the wrapped function name and docstring. Two smaller tools, total_ordering and singledispatch, round out the module.
The main program: fixing an argument with partial
The partial call takes a function and some of its arguments and returns a new callable that fills those arguments in on every call. The caller supplies only what is left:
import functools
def power(base, exponent):
return base ** exponent
square = functools.partial(power, exponent=2)
cube = functools.partial(power, exponent=3)
print(square(5))
print(cube(2))
print(square(3))
print(functools.partial(power, 2)(3))
The exact output:
25
8
9
8
The last line fixes the first argument instead of a keyword: partial with 2 as the base, called with 3, returns 2 raised to the 3rd power. A partial object is a plain callable, so it can go anywhere a function goes: a callback slot, a sort key, or a default in a table of operations.
Fixing words and overriding at call time
Fixed arguments can be positional or by keyword. Arguments the partial leaves open — including a parameter with a default, like punct here — are still supplied or overridden by the caller:
import functools
def greet(greeting, name, punct="!"):
return f"{greeting}, {name}{punct}"
hello = functools.partial(greet, "Hello")
print(hello("Ana"))
print(hello("Bo", punct="?"))
hi_ana = functools.partial(greet, "Hi", "Ana")
print(hi_ana())
print(hi_ana(punct="."))
print(hello.args)
print(hello.func.__name__)
The exact output:
Hello, Ana!
Hello, Bo?
Hi, Ana!
Hi, Ana.
('Hello',)
greet
The args attribute holds the positional arguments fixed in advance, and the func attribute holds the original function. Reading those two attributes is the fastest way to see what a partial object will actually call when code receives one from somewhere else.
Remembering results: lru_cache
The lru_cache decorator stores the result for each distinct set of arguments and returns the stored result on a later call with the same arguments. The classic case is a recursive function that would otherwise recompute the same values many times:
import functools
calls = []
@functools.lru_cache(maxsize=None)
def fib(n):
calls.append(n)
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
print(len(calls))
print(fib.cache_info())
fib.cache_clear()
print(fib.cache_info())
print(fib(5))
The exact output:
55
11
CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)
CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
5
The count that matters is len(calls): without the cache the body would run far more than 11 times for fib(10); with it, each distinct argument runs the body once. Setting maxsize to None removes the size limit; a numeric maxsize keeps only that many recent results and discards the least recently used ones. The cache_clear call empties the cache and resets the counts.
The short form: cache, and the typed switch
The cache decorator is lru_cache with no size limit and a simpler call. The typed argument on lru_cache controls whether values of different types that compare equal share one entry or keep separate entries:
import functools
@functools.cache
def add(a, b):
print("computing")
return a + b
print(add(2, 3))
print(add(2, 3))
print(add.cache_info())
@functools.lru_cache(maxsize=None, typed=True)
def ident(x):
return type(x).__name__
print(ident(1))
print(ident(1.0))
print(ident.cache_info())
The exact output:
computing
5
5
CacheInfo(hits=1, misses=1, maxsize=None, currsize=1)
int
float
CacheInfo(hits=0, misses=2, maxsize=None, currsize=2)
The word computing prints once: the second add call is a hit. With typed set to true, the integer 1 and the float 1.0 miss separately, even though they compare equal; with the default typed setting they would share a single entry. Cached arguments must be hashable — a later section shows the error an unhashable argument raises.
Folding a sequence: reduce
The reduce call applies a two-argument function step by step across a sequence, carrying a running total, and returns one final value. An optional starting value seeds the total and also covers the empty sequence:
import functools, operator
nums = [1, 2, 3, 4]
print(functools.reduce(operator.add, nums))
print(functools.reduce(operator.mul, nums, 10))
print(functools.reduce(operator.add, [], 0))
words = ["a", "b", "c"]
print(functools.reduce(lambda a, b: a + "-" + b, words))
try:
functools.reduce(operator.add, [])
except TypeError as e:
print(type(e).__name__)
The exact output:
10
240
0
a-b-c
TypeError
The operator module supplies add and mul so no lambda is needed for the common cases. The second line starts the product at 10, so the result is 240 rather than 24. The last lines show the trap: reduce on an empty sequence with no starting value raises TypeError, so any reduce over data that might be empty needs the starting value.
Keeping a wrapper honest: wraps
A decorator that returns a plain inner function replaces the wrapped function name and docstring with the inner ones. The wraps decorator, applied to the inner function, copies the name, docstring, and related attributes across, and sets a link back to the original:
import functools
def traced(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
"""Wrapper doc."""
return fn(*args, **kwargs)
return wrapper
@traced
def greet(name):
"""Say hello."""
return f"hello {name}"
print(greet("Ana"))
print(greet.__name__)
print(greet.__doc__)
print(greet.__wrapped__("Bo"))
The exact output:
hello Ana
greet
Say hello.
hello Bo
Without wraps, the name would read wrapper and the docstring would read Wrapper doc., and help output and error traces would point at the wrong function. The wrapped attribute reaches the original function directly, which test code uses to call the undecorated form.
Two smaller tools: total_ordering and singledispatch
The total_ordering decorator fills in the remaining comparison methods from one or two that a class defines. The singledispatch decorator builds a generic function that picks an implementation from the type of its first argument:
import functools
@functools.total_ordering
class Score:
def __init__(self, points):
self.points = points
def __eq__(self, other):
return isinstance(other, Score) and self.points == other.points
def __lt__(self, other):
return self.points < other.points
def __repr__(self):
return f"Score({self.points})"
a, b = Score(10), Score(20)
print(a < b)
print(a <= b)
print(b > a)
print(b >= a)
print(sorted([b, a]))
@functools.singledispatch
def describe(value):
return "other"
@describe.register
def _(value: int):
return "int"
@describe.register
def _(value: str):
return "str"
print(describe(3))
print(describe("x"))
print(describe(1.5))
try:
@functools.lru_cache(maxsize=None)
def f(x):
return x
f([1, 2])
except TypeError as e:
print(type(e).__name__)
The exact output:
True
True
True
True
[Score(10), Score(20)]
int
str
other
TypeError
The Score class defines only equality and less-than; total_ordering derives less-or-equal, greater, and greater-or-equal from those two. The generic describe function falls back to its base body for a float, because no float implementation was registered. The final lines return to the cache rule: a list argument is unhashable, so the cached call raises TypeError instead of a result.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Same call, one argument fixed | partial | Caller supplies only what changes |
| Costly pure function, repeated arguments | lru_cache or cache | Each distinct call runs once |
| Bounded memory for the cache | lru_cache with maxsize | Least recently used results are discarded |
| Fold a sequence to one value | reduce | Running total across the items |
| Write a decorator | wraps on the wrapper | Name and docstring survive |
| Class with full comparisons | total_ordering | Derive the rest from eq and one ordering |
| One function, behavior by type | singledispatch | Register one body per type |
Checklist
- Use partial when the same function is called repeatedly with one argument already known.
- Cache only pure functions: a cached call returns the stored result without running the body again.
- Give reduce a starting value whenever the sequence might be empty.
- Put wraps on every decorator wrapper, so help and traces name the real function.
- Keep cached arguments hashable: tuples and strings work, lists and dicts do not.
- Clear a cache with cache_clear when the underlying data changes under a long-running program.
Related guides on this site
- Python decorators — Writing and Using Decorators — the decorator form that wraps builds on.
- Python itertools — Count, Chain, Group, and Combine — the lazy iterators that pair with reduce and partial.
- Python sorting — sorted, sort, and key — key functions, a common place a partial object ends up.
- Python dataclasses — Fields, Defaults, and Equality — the generated equality and ordering that total_ordering mirrors by hand.
Sources
- Python Standard Library, functools — partial and partialmethod, lru_cache and cache with cache_info and cache_clear, reduce, wraps and update_wrapper, total_ordering, and singledispatch with register.
- Python Standard Library, operator — the add and mul functions passed to reduce.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.