Created
April 28, 2009 20:37
-
-
Save k0001/103388 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
import functools | |
class CallableCache(object): | |
def __init__(self, cache=None): | |
self._cache = cache or {} | |
def __call__(self, fn): | |
def w(*args, **kwargs): | |
try: | |
key = hash((fn, args, tuple(kwargs.items()))) | |
except TypeError, e: # non cacheable call | |
out = fn(*args, **kwargs) | |
else: | |
if key in self._cache: | |
return self._cache[key] | |
out = fn(*args, **kwargs) | |
self._cache[key] = out | |
return out | |
return functools.wraps(fn)(w) | |
callable_cache = CallableCache() | |
# usage: | |
# @callable_cache | |
# def f(foo, bar): | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment