lazy properties?

A

Andrea Crotti

Seeing the wonderful "lazy val" in Scala I thought that I should try to
get the following also in Python.
The problem is that I often have this pattern in my code:

class Sample:
def __init__(self):
self._var = None

@property
def var(self):
if self._var is None:
self._var = long_computation()
else:
return self._var


which is quite useful when you have some expensive attribute to compute
that is not going to change.
I was trying to generalize it in a @lazy_property but my attempts so far
failed, any help on how I could do that?

What I would like to write is
@lazy_property
def var_lazy(self):
return long_computation()

and this should imply that the long_computation is called only once..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top