Skip to content

Instantly share code, notes, and snippets.

@willium
Created January 30, 2017 00:37
Show Gist options
  • Save willium/1989e11abe2c91aae65fec6b76d9ab62 to your computer and use it in GitHub Desktop.
Save willium/1989e11abe2c91aae65fec6b76d9ab62 to your computer and use it in GitHub Desktop.
def memoize(fn):
cache = dict()
def closure(*args):
if args not in cache:
cache[args] = fn(*args)
return cache[args]
return closure
def memoize(f):
class memodict(dict):
def __getitem__(self, *key):
return dict.__getitem__(self, key)
def __missing__(self, key):
ret = self[key] = f(*key)
return ret
return memodict().__getitem__
@memoize
def foo(a, b):
return a * b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment