Skip to content

Instantly share code, notes, and snippets.

@leafsummer
Created November 30, 2018 10:34
Show Gist options
  • Save leafsummer/a229ff90be22277a3db4607037d81451 to your computer and use it in GitHub Desktop.
Save leafsummer/a229ff90be22277a3db4607037d81451 to your computer and use it in GitHub Desktop.
[python description for cache the property]
class cached_property(object):
"""
Decorator that converts a method with a single self argument into a
property cached on the instance.
Optional ``name`` argument allows you to make cached properties of other
methods. (e.g. url = cached_property(get_absolute_url, name='url') )
"""
def __init__(self, func, name=None):
self.func = func
self.__doc__ = getattr(func, '__doc__')
self.name = name or func.__name__
def __get__(self, instance, cls=None):
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment