Created
March 12, 2018 02:49
-
-
Save mgd020/c0c449070a4d6a2b2e8ee8fc0a2eb4a0 to your computer and use it in GitHub Desktop.
Method decorator which extends regular property to cache the value.
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
class cached_property(object): | |
"""Decorator that converts a method with a single self argument into a property cached on the instance.""" | |
def __init__(self, func): | |
self._get = func | |
self.__doc__ = getattr(func, '__doc__') | |
self._name = '_cached_' + func.__name__ | |
@staticmethod | |
def _set(obj, value): | |
raise AttributeError("can't set attribute") | |
def setter(self, func): | |
self._set = func | |
return self | |
def __get__(self, obj, cls): | |
if obj is None: | |
return self | |
try: | |
return obj.__dict__[self._name] | |
except KeyError: | |
pass | |
res = self._get(obj) | |
obj.__dict__[self._name] = res | |
return res | |
def __set__(self, obj, value): | |
self._set(obj, value) | |
obj.__dict__[self._name] = value | |
def __delete__(self, obj): | |
try: | |
del obj.__dict__[self._name] | |
except KeyError: | |
raise AttributeError(self._get.__name__) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment