Python functools: lru_cache, partial, and reduce in Practice
The functools module has a few functions I use constantly. Here is how lru_cache, partial, and reduce earn their place in my code. The functools module sits in the standard library and contains higher-order functions. functions that operate on other functions. I ignored it for a long time because the name sounded academic. After using lru_cache to speed up a slow recursive function and partial to clean up a callback API, it became a regular part of my toolkit. lru_cache for Memoization The lru_cache decorator caches function results. When the same arguments are passed again, it returns the cached value instead of recomputing. LRU stands for least recently used. when the cache is full, the oldest unused entry is evicted first. from functools import lru_cache @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n - 1) + fibonacci(n - 2) # First call computes, subsequent calls return cached fibonacci(50) # fast due to caching Without caching, fibonacci(50) makes over 2 billion recursive calls and takes minutes. With caching, it makes about 50 calls and finishes instantly. The cache key is built from the arguments, so all arguments must be hashable. lists…