Skip to content

Instantly share code, notes, and snippets.

@kindy61
Created September 24, 2009 03:22
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 kindy61/192491 to your computer and use it in GitHub Desktop.
Save kindy61/192491 to your computer and use it in GitHub Desktop.
#Recipe 325205: Cache decorator in python 2.4
#http://code.activestate.com/recipes/325205/, http://www.python.org/peps/pep-0318.html
def memoize(f, cache={}):
def g(*args, **kwargs):
key = ( f, tuple(args), frozenset(kwargs.items()) )
if key not in cache:
cache[key] = f(*args, **kwargs)
return cache[key]
return g
def safecall(f, default=None, exception=Exception):
'''Returns modified f. When the modified f is called and throws an
exception, the default value is returned'''
def _safecall(*args,**argv):
try:
return f(*args,**argv)
except exception:
return default
return _safecall
#[safecall(int)(i) for i in '1 2 x'.split()] # returns [1, 2, None]
#[safecall(int, -1, ValueError)(i) for i in '1 2 x'.split()] # returns [1, 2, -1]
if __name__ == '__main__':
@memoize
def f(n):
return (n<=2) and 1 or (f(n-1)+f(n-2))
f(40) # blindingly fast
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment