Skip to content

Instantly share code, notes, and snippets.

@clupasq
Created January 24, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clupasq/7cf6d0bd419a4a55bb92 to your computer and use it in GitHub Desktop.
Save clupasq/7cf6d0bd419a4a55bb92 to your computer and use it in GitHub Desktop.
Python memoisation decorator
# 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