Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #32572 > unrolled thread

lazy properties?

Started byAndrea Crotti <andrea.crotti.0@gmail.com>
First post2012-11-01 21:38 +0000
Last post2012-11-01 21:38 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python


Contents

  lazy properties? Andrea Crotti <andrea.crotti.0@gmail.com> - 2012-11-01 21:38 +0000

#32572 — lazy properties?

FromAndrea Crotti <andrea.crotti.0@gmail.com>
Date2012-11-01 21:38 +0000
Subjectlazy properties?
Message-ID<mailman.3165.1351806008.27098.python-list@python.org>
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..

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web