Created
January 24, 2015 21:49
-
-
Save clupasq/7cf6d0bd419a4a55bb92 to your computer and use it in GitHub Desktop.
Python memoisation decorator
This file contains 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
# taken from the "Design of Computer Programs" course by Peter Norvig | |
# https://www.udacity.com/course/cs212 | |
from functools import update_wrapper | |
def decorator(d): | |
"Make function d a decorator: d wraps a function fn." | |
def _d(fn): | |
return update_wrapper(d(fn), fn) | |
update_wrapper(_d, d) | |
return _d | |
@decorator | |
def memo(f): | |
"""Decorator that caches the return value for each call to f(args). | |
Then when called again with same args, we can just look it up.""" | |
cache = {} | |
def _f(*args): | |
try: | |
return cache[args] | |
except KeyError: | |
cache[args] = result = f(*args) | |
return result | |
except TypeError: | |
# some element of args refuses to be a dict key | |
return f(args) | |
_f.cache = cache | |
return _f | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment