Last active
August 22, 2017 01:56
-
-
Save TRManderson/1db074f0eda02c1645dc4b8e930d62d3 to your computer and use it in GitHub Desktop.
Cache decorator and cached property decorator
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
from functools import wraps | |
def cache(fn): | |
cache_dict = {} | |
@wraps(fn) | |
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) | |
@property | |
@wraps(fn) | |
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: | |
@result.setter | |
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