Skip to content

Instantly share code, notes, and snippets.

@eriwen
Created July 13, 2010 23:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eriwen/474749 to your computer and use it in GitHub Desktop.
Save eriwen/474749 to your computer and use it in GitHub Desktop.
Memoize Decorator in Python
def memoize(fn):
cache = {}
def wrapper(*args):
try:
return cache[args]
except:
result = fn(*args)
cache[args] = result
return result
return wrapper
# Example usage
@memoize
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment