The functools module gathers tools for working with functions. These are the three most useful ones.
reduce: combining a list into one value
reduce(function, list) applies a two-argument function to the accumulated value and the next element, from left to right:
from functools import reduce
numbers = [2, 3, 4]
product = reduce(lambda a, b: a * b, numbers)
print(product) # 24
# Step by step: (2 * 3) = 6, then (6 * 4) = 24
To add up or find the maximum you already have sum and max. reduce shines when the operation is your own, such as multiplying. Practice with Reduce a list to one value.
partial: fixing arguments
partial creates a new function from another one with some arguments already filled in:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5)) # 25
print(cube(2)) # 8
cache: not repeating calculations
@cache is a decorator that remembers results already calculated. Ideal for recursive functions such as Fibonacci:
from functools import cache
@cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60)) # 1548008755920
Common mistakes
1. Calling the function instead of passing it. apply(double(5)) passes the result of double(5); apply(double) passes the function.
def double(x):
return x * 2
print(list(map(double, [1, 2, 3]))) # [2, 4, 6]
# list(map(double(), [1, 2, 3])) # TypeError: missing argument
2. Forgetting the return in a decorator's wrapper. The decorated function would return None:
def bad(function):
def wrapper(*args, **kwargs):
function(*args, **kwargs) # return is missing
return wrapper
@bad
def add(a, b):
return a + b
print(add(2, 3)) # None
3. Mutable default values. A default value is created only once, when the function is defined. If it is a list, it is shared between calls:
def append_to(element, items=[]):
items.append(element)
return items
print(append_to(1)) # [1]
print(append_to(2)) # [1, 2] (the list was reused!)
The solution is to use None and create the list inside:
def append_to(element, items=None):
if items is None:
items = []
items.append(element)
return items
print(append_to(1)) # [1]
print(append_to(2)) # [2]
4. Closures in loops. Functions keep the *variable*, not its value at that moment:
functions = [lambda: i for i in range(3)]
print([f() for f in functions]) # [2, 2, 2] (all of them see the last i)
functions = [lambda i=i: i for i in range(3)]
print([f() for f in functions]) # [0, 1, 2]
Good practices
- Use
*argsand**kwargswhen you really need flexibility; if 2 values always arrive, write 2 parameters. - Put
@wrapsin all your decorators. - If a decorator or closure becomes hard to read, consider using a class or a normal function.
- Decorators should do one thing and do it well.