lazy evaluation of a variable

Terry Reedy tjreedy at udel.edu
Mon Jun 18 02:40:03 EDT 2012


On 6/17/2012 5:35 PM, Gelonida N wrote:

> I'm having a module, which should lazily evaluate one of it's variables.

If you literally mean a module object, that is not possible. On the 
other hand, it is easy to do with class instances, via the __getattr__ 
special method or via properties.

> 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

You could now do (untested, too late at night)
# mymodule.py
class _Lazy():
   def __getattr__(self, name):
     if name == 'var':
       self.var = something_time_consuming()
       return self.var

lazy = _Lazy()

# user script
from mymodule import lazy
def f():
   var = lazy.var

See Peter's post for using properties instead. That probably scales 
better for multiple lazy attibutes.

-- 
Terry Jan Reedy






More information about the Python-list mailing list