functools for caching, partial application, and more
functools contains several small tools with big practical payoff. The most useful ones in everyday code are lru_cache, partial, and cached_property.
Why it is useful
These tools help you avoid boilerplate:
lru_cachememoizes repeated function callspartialpre-fills some function argumentscached_propertycomputes a value once per instance
A few high-value patterns
Caching repeated pure work:
from functools import lru_cache
@lru_cache
def fibonacci(n: int) -> int:
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
Pre-filling arguments:
from functools import partial
int_base_2 = partial(int, base=2)
print(int_base_2("101"))
When to be careful
Caching only helps when repeated calls use the same inputs and the function behaves like a pure function. partial is handy, but not if it makes call sites more mysterious.
Rules of thumb
- Use
lru_cachefor repeated pure computations. - Use
partialwhen a configured function is clearer than a wrapper. - Use
cached_propertyfor expensive per-instance values.