Created
September 24, 2009 03:22
-
-
Save kindy61/192491 to your computer and use it in GitHub Desktop.
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
#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