Back to results for “Functional Programming”
Python › functools & Functional Programming Tools

What is the functools module used for in Python?

Beginner

Answer

functools provides higher-order functions that act on or return other functions, such as tools for caching (lru_cache, cache), partial application (partial), reducing sequences (reduce), and customizing comparisons (cmp_to_key, total_ordering). It centralizes common functional-programming utilities so you don't reimplement them.
import functools

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

print(fib(30))  # cached, fast
Real-world example A pricing service caches expensive tax-rate lookups per region using lru_cache to avoid repeated database hits.

Common follow-ups: What's the difference between functools.cache and lru_cache?;When would you avoid caching a function?