Skip to content

Instantly share code, notes, and snippets.

@mgd020
Created March 12, 2018 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgd020/c0c449070a4d6a2b2e8ee8fc0a2eb4a0 to your computer and use it in GitHub Desktop.
Save mgd020/c0c449070a4d6a2b2e8ee8fc0a2eb4a0 to your computer and use it in GitHub Desktop.
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__
@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