Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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__)
Add Comment
Please, Sign In to add comment