Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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()
expensive calculation
attrib_name = '_' + func.__name__
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