Python › functools & Functional Programming Tools
What is the functools module used for in Python?
BeginnerAnswer
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, fastReal-world example A pricing service caches expensive tax-rate lookups per region using lru_cache to avoid repeated database hits.