lazy evaluation of a variable

Jose H. Martinez josehmartinezz at gmail.com
Mon Jun 18 01:54:24 CEST 2012


Another option would be to refactor your function so that it is a generator
expression using the yield keyword.


On Sun, Jun 17, 2012 at 7:40 PM, Peter Otten <__peter__ at web.de> wrote:

> Gelonida N wrote:
>
> > I'm having a module, which should lazily evaluate one of it's variables.
> > Meaning that it is evaluated only if anybody tries to use this variable.
> >
> > At the moment I don't know how to do this and do therefore following:
> >
> >
> > ####### mymodule.py #######
> > var = None
> >
> > def get_var():
> >      global var
> >      if var is not None:
> >          return var
> >      var = something_time_consuming()
> >
> >
> >
> > Now the importing code would look like
> >
> > import mymodule
> > def f():
> >      var = mymodule.get_var()
> >
> > The disadvantage is, that I had to change existing code directly
> > accessing the variable.
> >
> >
> > I wondered if there were any way to change mymodule.py such, that the
> > importing code could just access a variable and the lazy evaluation
> > would happen transparently.
> >
> > import mymodule
> > def f():
> >      var = mymodule.var
> >
> >
> >
> > Thanks in advance for you suggestions
>
> You can inject arbitrary objects into sys.modules:
>
> >>> import sys
> >>> class MyModule(object):
> ...     def __init__(self):
> ...             self._var = None
> ...     @property
> ...     def var(self):
> ...             result = self._var
> ...             if result is None:
> ...                     print "calculating..."
> ...                     self._var = result = 42
> ...             return result
> ...
> >>> sys.modules["mymodule"] = MyModule()
> >>> import mymodule
> >>> mymodule.var
> calculating...
> 42
> >>> mymodule.var
> 42
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120617/89e95a82/attachment.html>


More information about the Python-list mailing list