Created
March 22, 2020 07:14
-
-
Save ychennay/fca233d4523ca0ffe22c8795d7fcb715 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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