Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Method decorator which extends regular property to cache the value.
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__
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
return obj.__dict__[self._name]
except KeyError:
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):
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
You can’t perform that action at this time.