Introduction
Functools provides higher-order functions and operations on callable objects.
LRU Cache
from functools import lru_cache
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Clear cache
fibonacci.cache_clear()
# Cache info
print(fibonacci.cache_info())
# CacheInfo(hits=0, misses=60, ...)
Partial 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)) # 25
print(cube(3)) # 27
Reducing Functions
from functools import reduce
# Reduce to single value
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result) # 120
Practice Problems
- Memoize recursive factorial
- Create partial function with positional args
- Use reduce for custom aggregations
- Implement caching decorator
- Create function composition with reduce