15. Functools Module
The functools module provides higher-order functions for working with other functions.
Common Functions
from functools import lru_cache, partial, reduce
@lru_cache(maxsize=None)
def fib(n):
if n < 2: return n
return fib(n-1) + fib(n-2)
print(fib(10))
def add(a, b): return a + b
add5 = partial(add, 5)
print(add5(10))
nums = [1, 2, 3, 4]
print(reduce(lambda x, y: x + y, nums))
Wrap-Up
functoolsoffers caching, partial functions, reducing, and more.