Advanced   Chapter 151 · 35 min read · Module 11: Advanced Python

functools

Learning objectives
  • After this chapter you can combine a sequence into one value with reduce.
  • You can create specialised functions with partial.
  • You can speed up repeated calls with lru_cache and cache.
  • You can write decorators that keep the original function name by using wraps.
  • You can explain what total_ordering, cmp_to_key and singledispatch are for.

In Python, functions are values. You can pass them to other functions, return them, and store them in variables. The standard library module functools collects tools that work on functions in exactly this way. They take a function and give you back a better or more specialised one.

Some of these tools save time, like lru_cache, which remembers results so the same work is not repeated. Some save typing, like partial, which fixes some arguments in advance. Others help you write careful decorators, such as wraps, or reduce a list to a single value, such as reduce.

In this chapter you will learn the most common functools tools with small runnable examples. You should already know how to define functions, use lambda, and write a simple decorator.

reduce: folding a sequence into one value

reduce(function, iterable, initial) takes the first two items, calls the function on them, then calls it again with that result and the next item, and so on. The final result is a single value. The optional initial value is placed before the first item and is also the answer for an empty sequence. Without it, an empty sequence raises TypeError.

Reduce (fold): repeatedly combining items of a sequence with a two-argument function until one value is left
Example 1: reduce to a sum, a product and a maximum
from functools import reduce

nums = [2, 3, 4]
print(reduce(lambda a, b: a + b, nums))
print(reduce(lambda a, b: a * b, nums, 10))
print(reduce(max, [7, 2, 9, 4]))
print(reduce(lambda a, b: a + b, [], 0))
9 240 9 0

For simple sums, sum() is clearer, and max() is clearer than reduce with max. Use reduce when no built-in does the job, for example when you merge a list of dictionaries.

partial: fix some arguments in advance

partial(func, *args, **kwargs) returns a new callable. When you call it, the stored arguments are supplied first and your new arguments are added after them. This is handy for callbacks and for map, where you need a function that takes one argument but your function takes two.

Example 2: building specialised functions
from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5), cube(2))
print(list(map(square, [1, 2, 3])))
to_binary = partial(int, base=2)
print(to_binary('1010'))
25 8 [1, 4, 9] 10

lru_cache and cache: remember results

Some functions do the same work again and again with the same inputs. lru_cache stores results in a dictionary keyed by the arguments. The next call with the same arguments returns the saved answer at once. LRU means least recently used: when the cache is full, the oldest unused entry is removed. lru_cache(maxsize=None) never removes anything, and @cache (Python 3.9+) is a short name for it.

Example 3: fast Fibonacci with a cache
from functools import lru_cache

calls = 0

@lru_cache(maxsize=None)
def fib(n):
    global calls
    calls += 1
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

print(fib(30))
print(calls)
print(fib.cache_info().hits)
832040 31 28
Cached functions need arguments that can be hashed, such as numbers, strings and tuples. A list argument raises TypeError. Also, only cache functions that always return the same result for the same input.

You can check how well the cache works with cache_info(). It reports hits (answers taken from the cache), misses (new calculations), the maximum size and the current size. In the example above, the plain recursive version of Fibonacci would call itself over a million times for fib(30), but the cached version computes each value only once. This idea of saving results is called memoisation, and it is one of the simplest ways to turn a slow recursive solution into a fast one.

If you ever need fresh results, for example in a unit test or after the underlying data changed, call fib.cache_clear(). This removes everything from the cache. Remember also that the cache keeps references to its arguments, so very large arguments stay in memory for as long as they are cached.

wraps: keep your decorator honest

A decorator replaces a function with a wrapper. Without care, the wrapper has its own name and docstring, which confuses debugging tools and help text. Adding @wraps(func) to the wrapper copies the name, docstring and other details from the original function.

Example 4: a decorator that keeps the function name
from functools import wraps

def shout(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout
def greet(name):
    """Say hello."""
    return 'hello ' + name

print(greet('mia'))
print(greet.__name__)
print(greet.__doc__)
HELLO MIA greet Say hello.

total_ordering, cmp_to_key and singledispatch

total_ordering is a class decorator. If you define __eq__ and one of <, <=, >, >=, it fills in the rest of the comparisons for you. cmp_to_key turns an old-style comparison function, which returns a negative, zero or positive number, into a key function for sorted. singledispatch lets one function name have different versions for different argument types.

Example 5: total_ordering and singledispatch
from functools import total_ordering, singledispatch

@total_ordering
class Version:
    def __init__(self, n):
        self.n = n
    def __eq__(self, other):
        return self.n == other.n
    def __lt__(self, other):
        return self.n < other.n

print(Version(1) <= Version(2), Version(3) > Version(2))

@singledispatch
def describe(x):
    return 'something'

@describe.register(int)
def _(x):
    return 'an integer'

@describe.register(list)
def _(x):
    return 'a list'

print(describe(5), describe([1]), describe(2.5))
True True an integer a list something

These tools are small, but together they let you write shorter code that is easy to reuse. Learn them one at a time and use them when a real problem matches.

Python syntax

Syntax
from functools import reduce, partial, lru_cache, wraps
Syntax
reduce(func, iterable, initial)
new_func = partial(func, arg1, key=value)
@lru_cache(maxsize=128)
def f(x): ...
@wraps(func)
def wrapper(*a, **k): ...

Real-world applications

  • Caching slow or repeated calculations such as recursive maths.
  • Pre-filling arguments for callbacks in GUI or event code.
  • Writing logging, timing or permission decorators that keep function names.
  • Sorting with custom comparison logic from older code.
  • Overloading a function by argument type.

Common mistakes

Mistake: Writing a decorator without @wraps, so the wrapped function shows the name 'wrapper'.
Fix: Add @wraps(func) above the inner wrapper function.
Mistake: Using lru_cache on a function that depends on changing outside data or the clock.
Fix: Cache only pure functions that always return the same output for the same input.
Mistake: Passing a list or dict to a cached function.
Fix: Use hashable arguments such as tuples, or convert before the call.
Mistake: Using reduce with no initial value on a possibly empty list.
Fix: Give an initial value, such as reduce(f, items, 0).

Important tips

  • Use @cache for simple unlimited caching on Python 3.9 and later.
  • Call func.cache_clear() when cached data must be refreshed, for example in tests.
  • Prefer sum, max and min over reduce when they fit.
  • partial objects keep .func, .args and .keywords so you can inspect them.

Key points summary

  • reduce folds a sequence into a single value.
  • partial returns a new function with some arguments fixed.
  • lru_cache remembers results for repeated calls.
  • wraps keeps the name and docstring of a decorated function.
  • singledispatch picks an implementation by the type of the first argument.

Exam and interview points

  • reduce(f, [a, b, c]) equals f(f(a, b), c).
  • lru_cache needs hashable arguments.
  • cache_info() shows hits, misses, maxsize and currsize.
  • partial fixed keyword arguments can still be overridden at call time.
  • total_ordering needs __eq__ and one ordering method.

Quick revision

  • reduce: fold to one value.
  • partial: pre-fill arguments.
  • lru_cache / cache: memoise.
  • wraps: preserve metadata.
  • total_ordering: fill comparisons.
  • singledispatch: choose by type.

Frequently asked questions

Is reduce still available in Python 3?

Yes, but it moved from the built-ins to functools. You must import it with from functools import reduce.

What does LRU in lru_cache mean?

Least Recently Used. When the cache reaches maxsize, the entry that has not been used for the longest time is removed to make room.

Is partial the same as a lambda?

They can do similar jobs. partial is shorter for fixing arguments, and it can be inspected and pickled more easily. A lambda is better when you need extra logic.

Why do I need wraps?

Without it, a decorated function loses its original __name__ and __doc__. That makes error messages, help() and debugging harder to read.

Practise this chapter

17 practice questions Take the chapter quiz

Related chapters