The built-in functools module contains tools that work on functions: they remember results, fix some arguments in advance, keep decorated functions tidy, and more. A few lines from functools can make a slow recursive function instant or replace a long chain of isinstance checks. This lesson covers the tools you are most likely to meet in real code.
In this lesson you will learn
- Caching results with
lru_cache - Fixing arguments with
partial - Folding a list with
reduce - Writing proper decorators with
wraps singledispatch,cached_propertyandtotal_ordering
You should know decorators, recursion and closures.
lru_cache, partial and reduce
from functools import lru_cache, partial, reduce
# lru_cache: remember results of earlier calls
calls = 0
@lru_cache(maxsize=None)
def ways(n):
"""Ways to climb n stairs taking 1 or 2 steps at a time."""
global calls
calls += 1
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)
print("ways(60) =", ways(60))
print("function bodies run:", calls)
print(ways.cache_info())
# partial: fix some arguments now, give the rest later
def price_with_tax(price, rate, discount=0):
return round(price * (1 - discount) * (1 + rate), 2)
bd_price = partial(price_with_tax, rate=0.15)
print("partial:", bd_price(1000), bd_price(1000, discount=0.1))
# reduce: fold a list into one value
nums = [3, 7, 2, 9, 4]
print("product:", reduce(lambda a, b: a * b, nums))
print("largest:", reduce(lambda a, b: a if a > b else b, nums))
Output
ways(60) = 2504730781961
function bodies run: 61
CacheInfo(hits=58, misses=61, maxsize=None, currsize=61)
partial: 1150.0 1035.0
product: 1512
largest: 9
ways(n)calls itself twice, so without help it would repeat the same work billions of times forn = 60.@lru_cachestores each result the first time it is computed. Later calls with the same argument return the stored answer, so the body runs only 61 times, once for each value from 0 to 60.cache_info()reports the hits (answers taken from the cache) and misses (answers that had to be computed).maxsize=Nonemeans the cache never throws anything away; a number such asmaxsize=128keeps only the most recently used results. Python 3.9 added@cacheas a short name for the unlimited version.partial(price_with_tax, rate=0.15)creates a new function with the rate already filled in. You call it with just the price, and can still pass the other arguments.reducecombines the items two at a time: first 3 × 7, then that result × 2, and so on, until one value is left. For sums and maxima, the built-inssumandmaxare clearer.
wraps, singledispatch, cached_property and total_ordering
from functools import wraps, singledispatch, cached_property, total_ordering
# wraps keeps the original name and docstring on a decorated function
def logged(func):
@wraps(func)
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
print(f" {func.__name__}{args} -> {result}")
return result
return wrapper
@logged
def area(w, h):
"""Area of a rectangle."""
return w * h
area(3, 4)
print("name:", area.__name__, "| doc:", area.__doc__)
# singledispatch: choose an implementation by the type of the first argument
@singledispatch
def describe(x):
return f"something else: {x!r}"
@describe.register
def _(x: int):
return f"integer with {len(str(abs(x)))} digits"
@describe.register
def _(x: list):
return f"list of {len(x)} items"
for value in (2026, [1, 2, 3], 3.5):
print(describe(value))
# cached_property: compute once per object, then reuse
class Report:
def __init__(self, sales):
self.sales = sales
@cached_property
def total(self):
print(" (adding up sales...)")
return sum(self.sales)
r = Report([1200, 800, 1500])
print(r.total, r.total)
# total_ordering: define == and < and get <=, >, >= free
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __eq__(self, other):
return self.parts == other.parts
def __lt__(self, other):
return self.parts < other.parts
print(Version("3.10") > Version("3.9"), Version("1.2") >= Version("1.2"))
Output
area(3, 4) -> 12
name: area | doc: Area of a rectangle.
integer with 4 digits
list of 3 items
something else: 3.5
(adding up sales...)
3500 3500
True True
- A decorator replaces a function with its
wrapper. Without@wraps(func),area.__name__would be “wrapper” and its docstring would be lost, which confuses help pages, debuggers and logs.@wrapscopies the original details across. @singledispatchmakes a generic function:describe.registeradds a version for each type, chosen by the type hint of the first argument. A float has no registered version, so the original function handles it.@cached_propertyruns the method the first time the attribute is read and stores the result on the object. The message “adding up sales” appears only once, even thoughr.totalis read twice. Use it for values that will not change during the object’s life.@total_orderingfills in<=,>and>=from your==and<. Comparing tuples of numbers also shows that version 3.10 is newer than 3.9, which a plain string comparison would get wrong.
functools at a Glance
| Tool | Use it to |
|---|---|
lru_cache / cache | Remember results of a pure function |
partial | Pre-fill some arguments of a function |
reduce | Fold a sequence into a single value |
wraps | Keep the name and docstring in decorators |
singledispatch | Pick an implementation by argument type |
cached_property | Compute an attribute once per object |
total_ordering | Get all comparisons from == and < |
Common Mistakes
- Caching a function with side effects, or one whose result depends on the time or a database. The cache returns old answers.
- Passing lists or dictionaries to an
lru_cachefunction. Arguments must be hashable, so this raisesTypeError; use tuples instead. - Forgetting
@wrapsin your own decorators. - Using
cached_propertyfor data that changes. The stored value is not updated when the underlying data changes.
Practice Exercises
Exercise 1. Use partial to make to_binary from the built-in int, so that to_binary("1011") returns 11.
Show answer
from functools import partial
to_binary = partial(int, base=2)
print(to_binary("1011")) # 11
Exercise 2. Use @cache to speed up a recursive function that returns the n-th Fibonacci number, and print fib(100).
Show answer
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(100)) # 354224848179261915075
Frequently Asked Questions
Why is it called LRU cache?
LRU stands for “least recently used”. When a limited cache is full, it throws away the result that has gone unused the longest, keeping the ones you need most often.
How do I clear an lru_cache?
Call cache_clear() on the decorated function, for example ways.cache_clear(). This is useful in tests or when the underlying data has changed.
Summary
lru_cacheandcacheturn repeated work into instant lookups.partialpre-fills arguments;reducefolds a list into one value.- Always use
@wrapsinside decorators. singledispatch,cached_propertyandtotal_orderingremove boilerplate code.
Next: Python Enum.
