Python's functools Module: Higher-Order Functions and Decorators
Table of Contents
1. Introduction to functools
The functools module is a standard Python library that provides higher-order functions and operations on callable objects.
2. Key Functions
2.1. partial
verified
The partial function allows you to fix a certain number of arguments of a function and generate a new callable.
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(3)) # 27
2.2. reduce
verified
The reduce function applies a binary function cumulatively to items in an iterable, reducing it to a single value.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
2.3. lru_cache
verified
The lru_cache decorator implements memoization using a Least Recently Used cache strategy.
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(100)) # Computed efficiently
2.4. wraps
verified
The wraps decorator preserves metadata when creating wrapper functions.
from functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@my_decorator
def greet(name):
"""Greet someone by name"""
return f"Hello, {name}"
print(greet.__name__) # 'greet'
print(greet.__doc__) # 'Greet someone by name'
4. Related
- Itertools Tutorial – the other half of the functional standard library
- Python Asterisk Operator – unpacking, which partial leans on
- Lambda Calculus Implementation in Python – higher-order functions from first principles
- Dynamic Programming Tutorial – lru_cache at work