Created
May 13, 2022 21:10
-
-
Save mrtj/0e64599ff1245a81d2c0a80c4337b261 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
import functools | |
def lazy_property(func): | |
''' Caches the return value of a function, and turns it into a property. | |
Intended to be used as a function decorator:: | |
>>> class Foo: | |
>>> @lazy_property | |
>>> def bar(self): | |
>>> print('expensive calculation') | |
>>> return 'bar' | |
>>> foo = Foo() | |
>>> foo.bar() | |
expensive calculation | |
'bar' | |
>>> foo.bar() | |
'bar' | |
''' | |
attrib_name = '_' + func.__name__ | |
@property | |
@functools.wraps(func) | |
def lazy_wrapper(instance, *args, **kwargs): | |
if hasattr(instance, attrib_name): | |
return getattr(instance, attrib_name) | |
value = func(instance, *args, **kwargs) | |
object.__setattr__(instance, attrib_name, value) | |
return value | |
return lazy_wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment