How would you implement a caching/memoization decorator from scratch, similar to functools.lru_cache?
Short answer
Maintain a dictionary (closure variable or instance attribute) mapping argument tuples to previously-computed results; the wrapper checks the cache first and only calls the real function (storing the new result) on a cache miss — must handle unhashable arguments carefully, since…
Advertisement
AModel answer
Maintain a dictionary (closure variable or instance attribute) mapping argument tuples to previously-computed results; the wrapper checks the cache first and only calls the real function (storing the new result) on a cache miss — must handle unhashable arguments carefully, since dict keys require hashability.
def memoize(func):
cache = {}
@functools.wraps(func)
def wrapper(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return wrapper
@memoize
def fibonacci(n):
if n < 2: return n
return fibonacci(n - 1) + fibonacci(n - 2)Real-world example
Building a custom caching decorator with specialized eviction logic that functools.lru_cache's simple LRU policy doesn't support.
Likely follow-ups
- What happens if this memoize decorator is applied to a function called with UNHASHABLE arguments, like a list?
Related topics