Skip to content

Instantly share code, notes, and snippets.

@k0001
Created April 28, 2009 20:37
Show Gist options
  • Save k0001/103388 to your computer and use it in GitHub Desktop.
Save k0001/103388 to your computer and use it in GitHub Desktop.
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