Created
May 13, 2022 21:10
-
-
Save mrtj/0e64599ff1245a81d2c0a80c4337b261 to your computer and use it in GitHub Desktop.
Revisions
-
mrtj created this gist
May 13, 2022 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,29 @@ 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