Skip to content

Instantly share code, notes, and snippets.

@ychennay
Created March 22, 2020 07:14
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 ychennay/fca233d4523ca0ffe22c8795d7fcb715 to your computer and use it in GitHub Desktop.
Save ychennay/fca233d4523ca0ffe22c8795d7fcb715 to your computer and use it in GitHub Desktop.
class cached_property:
'''
Decorator that converts a method with a single self argument into a
property cached on the instance.
A cached property can be made out of an existing method:
(e.g. ``url = cached_property(get_absolute_url)``).
'''
# ...
def __get__(self, instance, cls=None):
"""
Call the function and put the return value in instance.__dict__ so that
subsequent attribute access on the instance returns the cached value
instead of calling cached_property.__get__().
"""
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