Skip to content

Instantly share code, notes, and snippets.

@mrtj
Created May 13, 2022 21:10
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 mrtj/0e64599ff1245a81d2c0a80c4337b261 to your computer and use it in GitHub Desktop.
Save mrtj/0e64599ff1245a81d2c0a80c4337b261 to your computer and use it in GitHub Desktop.
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