Cache decorator python
Memoize (cache) a function in Python by using this decorator:
1from functools import wraps
2
3def memoize(func):
4 cache = {}
5 @wraps(func)
6 def wrapper(*args):
7 if args in cache:
8 return cache[args]
9 else:
10 result = func(*args)
11 cache[args] = result
12
13 return result
14
15 return wrapper
References
#snippets #code #tricks #cache #caching #python #computer_science #programming