Python functools Explained: lru_cache, partial, reduce, wraps and More, Tested
Python functools is the standard library toolbox for working with functions: caching results, pre-filling arguments, folding lists, writing proper decorators and dispatching on type. Here is what each tool does, with output we ran on Python 3.13.
- Python functools is built in; the most useful tools are
lru_cache,partial,wrapsandcached_property. - Caching a recursive Fibonacci cut
fib(30)from 0.106 seconds to 0.137 milliseconds in our run. - Without
@wraps, our decorated function reported its name asinnerand lost its docstring. - Cached functions need hashable arguments: passing a list raised
TypeError.
Sooner or later every Python developer writes a slow function that gets called with the same inputs, a decorator that breaks debugging, or a lambda whose only job is to fix one argument. The Python functools module solves all three with a few well-tested tools. You do not need to install anything; it ships with every Python version you are likely to use.
All examples here were run on Python 3.13.6 and the printed output is copied from that run. Timings depend on hardware, so focus on the ratios. Decorators come up a lot below, so if they are new to you, start with our Python decorators guide.
What is functools?
functools is a standard library module for higher-order functions: functions that take or return other functions. It groups tools into three families:
- Caching:
lru_cache,cacheandcached_propertyremember results. - Building functions:
partial,reduceandsingledispatchcreate or combine behaviour. - Helpers for classes and decorators:
wrapsandtotal_orderingfill in boilerplate.
lru_cache and cache: memoize slow functions
lru_cache stores the result for each set of arguments. The next call with the same arguments returns the stored value instead of recomputing it. Recursive functions with overlapping sub-problems benefit the most:
from functools import lru_cache
def fib_plain(n):
return n if n < 2 else fib_plain(n - 1) + fib_plain(n - 2)
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
fib(30)
print(fib.cache_info())
fib(30) plain 0.106s cached 0.137ms
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
The plain version makes over a million calls for n = 30. The cached one computed each value from 0 to 30 once (31 misses) and served the rest from the cache (28 hits). That turned roughly a tenth of a second into well under a millisecond.
Since Python 3.9, @cache is a shorter spelling of @lru_cache(maxsize=None): an unbounded cache with slightly less overhead. Use cache_info() to check hit rates and cache_clear() to empty the cache, for example between tests.
How maxsize really works
LRU stands for “least recently used”. When a bounded cache is full, the entry that was used longest ago is evicted. We set maxsize=2 and called a counting function with the inputs 1, 2, 1, 3, 1, 2:
@lru_cache(maxsize=2)
def sq(x):
global calls
calls += 1
return x * x
for x in [1, 2, 1, 3, 1, 2]:
sq(x)
print(calls, sq.cache_info())
4 CacheInfo(hits=2, misses=4, maxsize=2, currsize=2)
Walk through it: 1 and 2 are misses. The second 1 is a hit. Then 3 is a miss and evicts 2, the least recently used. The third 1 is a hit, and the final 2 is a miss again because it was evicted. Choose maxsize from real usage; a cache that is too small keeps throwing away exactly what you need next.
Tip: only cache pure functions, whose result depends only on their arguments. Caching a function that reads the clock, a database or a file will return stale data.
partial: pre-fill arguments
partial creates a new callable with some arguments already fixed. It is clearer than a one-line lambda and easier to inspect:
from functools import partial
pow2 = partial(pow, exp=2)
print(pow2(9)) # 81
int_bin = partial(int, base=2)
print(int_bin("1011")) # 11
print(int_bin.func.__name__, int_bin.keywords) # int {'base': 2}
The func, args and keywords attributes let you see what was fixed, which a lambda hides. Typical uses are callbacks for GUI buttons, pre-configured loggers and passing a configured function to map or a thread pool. If you prefer lambdas for one-off cases, our Python lambda functions guide compares the two styles.
reduce: fold a sequence into one value
reduce applies a two-argument function cumulatively from left to right. It moved from the built-ins into functools in Python 3:
from functools import reduce
import operator
print(reduce(operator.mul, [1, 2, 3, 4, 5])) # 120
print(reduce(operator.add, [], 0)) # 0
reduce(operator.add, [])
TypeError: reduce() of empty iterable with no initial value
Always pass an initial value when the input could be empty. And check for a built-in first: sum, max, min, any, all and math.prod are clearer than reduce for the common cases. Keep reduce for genuinely custom folds, such as merging a list of dictionaries.
wraps: decorators that keep their identity
A decorator replaces a function with a wrapper. Without help, the wrapper’s name and docstring replace the original’s, which breaks logs, documentation and test reports. We decorated the same function with and without @wraps:
from functools import wraps
def nowrap(f):
def inner(*a, **k):
return f(*a, **k)
return inner
def withwrap(f):
@wraps(f)
def inner(*a, **k):
return f(*a, **k)
return inner
no wraps: inner None
wraps: greet2 Say hello. greet2
With @wraps(f), the wrapper copies __name__, __doc__, __module__ and more, and adds __wrapped__ so tools can reach the original. Put it in every decorator you write; there is no downside.
cached_property: compute once per object
cached_property turns a method into an attribute that is computed on first access and then stored on the instance:
from functools import cached_property
class Report:
def __init__(self, rows):
self.rows, self.n = rows, 0
@cached_property
def total(self):
self.n += 1
return sum(self.rows)
r = Report([1, 2, 3])
r.total; r.total
print(r.n, r.total) # 1 6
The property body ran once even though we read it three times. Because the value is stored in the instance dictionary, deleting it with del r.total forces a recompute. It suits expensive values that do not change during an object’s life, such as a parsed config. For more on classes, see our Python classes and objects guide.
singledispatch: one function, many types
singledispatch picks an implementation based on the type of the first argument, which replaces long isinstance chains:
from functools import singledispatch
@singledispatch
def fmt(x):
return f"obj:{x}"
@fmt.register
def _(x: int):
return f"int:{x:,}"
@fmt.register
def _(x: list):
return "list:" + ",".join(map(fmt, x))
print(fmt(1234567), fmt([1, "a"]), fmt(2.5))
int:1,234,567 list:int:1,obj:a obj:2.5
Registration reads the type hint, so the code stays tidy. New types can be added from other modules without touching the original function. For methods, use singledispatchmethod. Type hints in general are covered in our Python type hints guide.
total_ordering: fewer comparison methods
Define __eq__ and one of __lt__, __le__, __gt__ or __ge__, and @total_ordering fills in the rest. In our test, a version class with only __eq__ and __lt__ answered Ver(1,2) >= Ver(1,1) with True and Ver(1,2) <= Ver(1,1) with False. The generated methods are a little slower than hand-written ones, so skip it in very hot code.
Pitfalls to avoid
- Unhashable arguments. Cached functions build a key from the arguments. Calling a cached function with a list raised
TypeError: unhashable type: 'list'in our run. Convert to a tuple first. - Caching methods.
lru_cacheon an instance method includesselfin the key and keeps every instance alive as long as the cache does. Prefercached_propertyor a module-level cached function. - Unbounded memory.
@cachenever evicts. For inputs from users or the network, set amaxsize. - Mutable results. A cached list or dict is shared by every caller. If one caller changes it, everyone sees the change.
- Stale caches in tests. Call
cache_clear()in a fixture so one test cannot leak results into another.
Python functools cheat sheet
| Tool | Use it to | Since |
|---|---|---|
lru_cache |
Memoize with a size limit | 3.2 |
cache |
Memoize without a limit | 3.9 |
cached_property |
Compute an attribute once per object | 3.8 |
partial |
Fix some arguments of a function | 2.5 |
reduce |
Fold a sequence into one value | moved in 3.0 |
wraps |
Keep metadata in decorators | 2.5 |
singledispatch |
Choose an implementation by type | 3.4 |
total_ordering |
Generate comparison methods | 2.7 |
Final thoughts
Python functools rewards a small investment. Add @wraps to every decorator, reach for lru_cache or cache when a pure function repeats work, and replace argument-fixing lambdas with partial. Our measurements showed the payoff clearly: one decorator line made a recursive function several hundred times faster. Pair these tools with Python generators and you will write shorter, faster, more readable code.
Frequently asked questions
What is the difference between lru_cache and cache?
cache is an unbounded cache, the same as lru_cache with maxsize set to None. lru_cache accepts a maxsize and evicts the least recently used entry when it is full.
Why does lru_cache raise TypeError: unhashable type?
The cache uses the arguments as a dictionary key, so they must be hashable. Lists, dicts and sets are not; convert them to tuples or frozensets before calling.
Why should I use functools.wraps in decorators?
Without it, the decorated function takes the wrapper’s name and loses its docstring, which confuses logs, help text and test reports. wraps copies that metadata across.
Is functools.partial better than a lambda?
For fixing arguments, usually yes. A partial object is clearer, can be pickled when its function can, and exposes func, args and keywords for inspection.
Is reduce still recommended in Python 3?
Use it sparingly. Built-ins such as sum, max, min, any, all and math.prod are clearer for common cases; keep reduce for custom folds and always give an initial value.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.