Python Standard Library · Lesson 120 of 149

Python functools

What you will learn

  • Speeding up repeated calls with lru_cache and cache
  • Fixing arguments with partial
  • Folding a sequence with reduce
  • Keeping metadata in decorators with wraps
  • Type-based functions with singledispatch
  • cmp_to_key and cached_property

1. Tools for functions

Functions are values in Python (lesson 11.7), and the functools module collects helpers that take functions and return improved ones. Several are decorators (lesson 11.11).

from functools import lru_cache, cache, partial, reduce, wraps, singledispatch, cmp_to_key

2. Remembering results: cache and lru_cache

Some functions are called many times with the same arguments, and recompute the same answer. The Fibonacci function written with plain recursion does that (lesson 11.6):

calls = 0

def fib_slow(n):
    global calls
    calls += 1
    return n if n < 2 else fib_slow(n - 1) + fib_slow(n - 2)

print(fib_slow(20), calls)
6765 21891

Just to compute the 20th number, the function ran 21,891 times. Caching (memoization) stores each result the first time, and reuses it:

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

print(fib(80))
print(fib.cache_info())
23416728348467685
CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)

Each of the 81 different arguments (0 to 80) was computed once (a miss); the other 78 calls were answered from memory (hits). Without the cache, fib(80) would take longer than a lifetime. The decorator @lru_cache ("least recently used" cache) takes maxsize: the number of results to keep. When the cache is full, the least recently used entry is thrown away. @cache (Python 3.9+) is shorthand for an unlimited cache:

@cache
def sq(x):
    print("computing", x)
    return x * x

print(sq(4), sq(4), sq(5))
computing 4
computing 5
16 16 25

The second sq(4) printed nothing: it came from the cache.

@lru_cache(maxsize=2)
def f(x):
    return x

f(1); f(2); f(3); f(1)
print(f.cache_info())
CacheInfo(hits=0, misses=4, maxsize=2, currsize=2)

With room for only 2 entries, 1 had been pushed out by the time it was asked for again, so the last call was another miss.

Other details:

  • fib.cache_clear() empties the cache; fib.cache_info() shows statistics; fib.__wrapped__(10) calls the original, uncached function.
  • Arguments must be hashable (lesson 9.7), because they are used as dictionary keys:
@cache
def bad(lst):
    return sum(lst)

bad([1, 2])
TypeError: unhashable type: 'list'

Use tuples instead of lists. - Only cache pure functions: same arguments, same result, no side effects. Caching a function that reads the clock or a file returns stale answers. - A cache holds on to memory; bound it with maxsize for long-running programs.

Quick check: what does a cache "hit" mean?

The result for those arguments was already stored, so the function body did not run again.

3. partial: pre-filling arguments

partial(func, *args, **kwargs) makes a new function with some arguments already fixed:

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

square = partial(power, exp=2)
cube = partial(power, exp=3)
two_to = partial(power, 2)

print(square(5), cube(2), two_to(10))
print(square.func.__name__, square.keywords, two_to.args)
25 8 1024
power {'exp': 2} (2,)

square(5) calls power(5, exp=2). A partial is handy as a callback or with map (lesson 11.7), where you may only pass the function name:

print(list(map(partial(int, base=2), ["101", "11"])))
[5, 3]

(Reading binary numbers: "101" is 5, "11" is 3.) Often a lambda does the same, but partial is clearer and can be inspected (.func, .args, .keywords).

4. reduce: folding a sequence

reduce(function, iterable, initial) applies a two-argument function cumulatively, boiling a sequence down to one value:

import operator

print(reduce(operator.add, [1, 2, 3, 4]))
print(reduce(lambda a, b: a * b, [1, 2, 3, 4], 10))
print(reduce(max, [3, 9, 2]))
print(reduce(lambda a, b: a + b, [], 0))
10
240
9
0

Step by step, reduce(add, [1, 2, 3, 4]) computes ((1 + 2) + 3) + 4. The third argument is the starting value: 10 * 1 * 2 * 3 * 4 = 240, and it is the result for an empty sequence. Without it, an empty input fails:

reduce(operator.add, [])
TypeError: reduce() of empty iterable with no initial value

reduce is rarely the clearest choice: sum, max, min, any, all and "".join cover its common uses. It shines for merging dictionaries or chaining functions:

print(reduce(lambda a, b: {**a, **b}, [{"a": 1}, {"b": 2}, {"a": 3}]))
{'a': 3, 'b': 2}

(Later dictionaries win, lesson 9.5.)

5. wraps: well-behaved decorators

A decorator replaces a function by a wrapper, and the wrapper's name and docstring replace the original's unless you copy them. The decorator wraps does that copy:

def timed(fn):
    @wraps(fn)
    def wrapper(*a, **k):
        return fn(*a, **k)
    return wrapper

def timed_bad(fn):
    def wrapper(*a, **k):
        return fn(*a, **k)
    return wrapper

@timed
def greet(name):
    "Say hello."
    return f"hi {name}"

@timed_bad
def greet2(name):
    "Say hello."
    return f"hi {name}"

print(greet.__name__, "|", greet.__doc__)
print(greet2.__name__, "|", greet2.__doc__)
print(greet.__wrapped__("x"))
greet | Say hello.
wrapper | None
hi x

Without wraps, help(greet2) and error messages show the useless name wrapper. With it, the original keeps its identity and is available as __wrapped__. Always use @wraps(fn) inside your own decorators (lesson 11.11).

6. singledispatch: one name, several types

singledispatch chooses an implementation by the type of the first argument, a tidy replacement for a chain of isinstance checks:

@singledispatch
def show(x):
    return f"object {x!r}"

@show.register
def _(x: int):
    return f"int {x}"

@show.register(list)
def _(x):
    return f"list of {len(x)}"

print(show(3), "|", show([1, 2]), "|", show("s"), "|", show(2.5))
int 3 | list of 2 | object 's' | object 2.5

The base function is the default; register adds versions for particular types (given by an annotation or an argument). Types without their own version (str, float) fall back to the default. It is a form of polymorphism for functions you do not want as methods (lesson 13.6).

7. cmp_to_key and cached_property

Old-style comparison functions return a negative, zero or positive number. sorted wants a key function instead; cmp_to_key converts one to the other:

def by_len_then_alpha(a, b):
    return (len(a) > len(b)) - (len(a) < len(b)) or (a > b) - (a < b)

print(sorted(["bb", "a", "ab", "c"], key=cmp_to_key(by_len_then_alpha)))
['a', 'c', 'ab', 'bb']

(Usually a key like key=lambda s: (len(s), s) is simpler; use cmp_to_key for existing comparison code.)

cached_property (lesson 13.14) computes a method once per object and stores it as an attribute:

from functools import cached_property

class C:
    def __init__(self):
        self.n = 0

    @cached_property
    def heavy(self):
        self.n += 1
        return 42

c = C()
print(c.heavy, c.heavy, c.n)
42 42 1

@total_ordering (lesson 13.8) is also in functools.

Worked example: caching, partial and a pipeline

Count walking routes across a grid with a cache, fix a tax rate with partial while counting calls through a wraps decorator, and build a text "slug" by folding a list of step functions.

from functools import cache, partial, reduce, wraps
import operator


@cache
def paths(rows, cols):
    """Ways to walk from top-left to bottom-right moving only right or down."""
    if rows == 1 or cols == 1:
        return 1
    return paths(rows - 1, cols) + paths(rows, cols - 1)


print(paths(3, 3), paths(10, 10), paths(18, 18))
print(paths.cache_info())


def counted(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        wrapper.calls += 1
        return fn(*args, **kwargs)
    wrapper.calls = 0
    return wrapper


@counted
def add_tax(price, rate):
    """Price including tax."""
    return round(price * (1 + rate), 2)


vat = partial(add_tax, rate=0.15)
print([vat(p) for p in (10, 20, 30)], add_tax.calls, add_tax.__name__, add_tax.__doc__)

steps = [str.strip, str.lower, lambda s: s.replace(" ", "-")]
slug = lambda text: reduce(lambda value, step: step(value), steps, text)
print(slug("  Hello Big World "))

print(reduce(operator.mul, range(1, 6)))
6 48620 2333606220
CacheInfo(hits=258, misses=323, maxsize=None, currsize=323)
[11.5, 23.0, 34.5] 3 add_tax Price including tax.
hello-big-world
120
Part Idea
@cache on paths 323 different (rows, cols) pairs computed once each; 258 repeated requests answered from memory
wrapper.calls a counter stored on the wrapper function itself (functions can have attributes)
@wraps(fn) add_tax.__name__ and its docstring survive decoration
partial(add_tax, rate=0.15) a ready-made vat function; all three calls were counted
reduce over steps feeds the text through each function in turn

The prices and the 15 percent rate are made up for the lesson.

Common mistakes

  • Caching a function with side effects, or one that depends on changing data.
  • Passing lists or dictionaries to a cached function (unhashable).
  • An unlimited cache in a long-running program, using up memory.
  • Forgetting @wraps in decorators.
  • Using reduce where sum, max or "".join is clearer.
  • Calling reduce on an empty sequence without an initial value.
  • Forgetting that partial fixes positional arguments from the left.

Key takeaways

  • @cache / @lru_cache remember results, turning repeated or recursive work into fast lookups; arguments must be hashable and the function pure.
  • partial fixes some arguments to make a new function.
  • reduce(f, items, initial) folds a sequence into one value; prefer built-ins when they fit.
  • Use @wraps(fn) in every decorator so names and docstrings survive.
  • singledispatch selects an implementation by argument type; cmp_to_key adapts comparison functions; cached_property computes once per object.

Practice

1. What does lru_cache(maxsize=128) do when the 129th different argument arrives?

Show answer

It discards the least recently used cached result to make room.

2. Create a function to_binary from int that parses base-2 text.

Show answer

to_binary = partial(int, base=2); to_binary("101") is 5.

3. What is reduce(operator.mul, [2, 3, 4])?

Show answer

24, which is (2 * 3) * 4.

4. What goes wrong if a decorator omits @wraps?

Show answer

The decorated function reports the wrapper's name and loses its docstring, which confuses help and debugging.

5. Why can't you call a cached function with a list argument?

Show answer

Arguments become dictionary keys, and lists are unhashable. Pass a tuple.

6. When is singledispatch useful?

Show answer

When one function should behave differently depending on the type of its first argument, replacing a chain of isinstance tests.