Created
August 27, 2018 20:00
-
-
Save NatiAris/ed0abc33594352a16d745b4320750f58 to your computer and use it in GitHub Desktop.
A simple decorator adding memoization to a function. Only works with positional arguments. Way too simplistic to have a limit on cache size, so be careful.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import functools | |
| def memoize(outer_func): | |
| """Memoize everything.""" | |
| @functools.wraps(outer_func) | |
| def inner_func(*args, _cache={}): | |
| if args in _cache: | |
| return _cache[args] | |
| _cache[args] = outer_func(*args) | |
| return _cache[args] | |
| return inner_func |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can access the accumulated cache through
func.__kwdefaults__['_cache']and re-use by passing as_cachekeyword argument.