Skip to content

Instantly share code, notes, and snippets.

@TRManderson TRManderson/
Last active Aug 22, 2017

What would you like to do?
Cache decorator and cached property decorator
from functools import wraps
def cache(fn):
cache_dict = {}
def result(*args, **kwargs):
# can't cache kwargs
assert not kwargs
if args not in cache_dict:
cache_dict[args] = fn(*args)
return cache_dict[args]
result.cache = cache_dict
return result
def cached_property(fn=None, allow_set=None):
if allow_set is not None:
return lambda f: cached_property(f, allow_set)
def result(self):
self._property_cache = getattr(self, '_property_cache', {})
if fn.__name__ not in self._property_cache:
self._property_cache[fn.__name__] = fn(self)
return self._property_cache[fn.__name__]
if allow_set:
def result(self, val):
self._property_cache = getattr(self, '_property_cache', {})
self._property_cache[fn.__name__] = val
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.