Memoize decorator in Python
Memoization trades memory for speed - standard for expensive pure functions.
def memoize(fn):
cache = {}
def wrapper(*args):
if args not in cache:
cache[args] = fn(*args)
return cache[args]
return wrapper
How it works
- Wraps a function in a decorator.
- A
dictcaches each result, keyed by the call's arguments. - Repeat calls with the same arguments return the cached value instantly.
Keywords and builtins used here
defifmemoizereturnwrapper
The run, in numbers
- Lines
- 9
- Characters to type
- 129
- Tokens
- 40
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 23 seconds.
Step 4 of 5 in Decorators & closures, step 8 of 53 in Pythonic Python.