<span style>Another option would be to refactor your function so that it is a generator expression using the yield keyword. </span><div class="yj6qo ajU" style><br class="Apple-interchange-newline"></div><br><div class="gmail_quote">
On Sun, Jun 17, 2012 at 7:40 PM, Peter Otten <span dir="ltr"><<a href="mailto:__peter__@web.de" target="_blank">__peter__@web.de</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">Gelonida N wrote:<br>
<br>
> I'm having a module, which should lazily evaluate one of it's variables.<br>
> Meaning that it is evaluated only if anybody tries to use this variable.<br>
><br>
> At the moment I don't know how to do this and do therefore following:<br>
><br>
><br>
> ####### mymodule.py #######<br>
> var = None<br>
><br>
> def get_var():<br>
>      global var<br>
>      if var is not None:<br>
>          return var<br>
>      var = something_time_consuming()<br>
><br>
><br>
><br>
> Now the importing code would look like<br>
><br>
> import mymodule<br>
> def f():<br>
>      var = mymodule.get_var()<br>
><br>
> The disadvantage is, that I had to change existing code directly<br>
> accessing the variable.<br>
><br>
><br>
> I wondered if there were any way to change mymodule.py such, that the<br>
> importing code could just access a variable and the lazy evaluation<br>
> would happen transparently.<br>
><br>
> import mymodule<br>
> def f():<br>
>      var = mymodule.var<br>
><br>
><br>
><br>
> Thanks in advance for you suggestions<br>
<br>
</div>You can inject arbitrary objects into sys.modules:<br>
<br>
>>> import sys<br>
>>> class MyModule(object):<br>
...     def __init__(self):<br>
...             self._var = None<br>
...     @property<br>
...     def var(self):<br>
...             result = self._var<br>
...             if result is None:<br>
...                     print "calculating..."<br>
...                     self._var = result = 42<br>
...             return result<br>
...<br>
>>> sys.modules["mymodule"] = MyModule()<br>
>>> import mymodule<br>
>>> mymodule.var<br>
calculating...<br>
42<br>
>>> mymodule.var<br>
42<br>
<span class="HOEnZb"><font color="#888888"><br>
<br>
--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br>