what is it, that I don't understand about python and lazy evaluation?

Dave Angel davea at ieee.org
Thu Aug 13 11:34:23 EDT 2009



Antoine Pitrou wrote:
> Erik Bernoth <erik.bernoth <at> googlemail.com> writes:
>   
>> Isn't it strange, that this code runs (in a lazy language) for eternity?
>>     
>
> Python is a not a lazy language.
> `and` and `or` are particular, they are language constructs (*), not operators,
> that's why they can decide whether or not to evaluate their second term. It's a
> feature, but this feature is not general to Python.
>
> (*) by this I mean they have similar status as, for example, `if` and `else`
>
>
>
>   
Agreed.

In fact, I don't know of any aspect of Python which I'd call lazy, 
although the word appears in the docs in a few places.  I've seen, but 
not used, languages which had lazy evaluations.  Simplest example would 
be an infinite precision math package, where the actual precision is not 
actually used till something external to the program got visibility to 
the value.  So the constant PI might really be a generator, which would 
generate enough precision for whatever the value was being used for.  If 
you did a free-form print of PI, the console would never terminate (in 
principle), but in practice, it'd get slower and slower printing out the 
digits till the machine ran out of memory, or the user lost patience.

Python, on the other hand has at least three short-circuit operations, 
in which parts of the expression are defined not to be evaluated at all, 
if other parts meet certain conditions.  These are the 'and' and 'or' 
keywords mentioned above, the chained comparison construct, and the 
conditional expression, added recently.  In each of these, the semantics 
of the language require that those parts not be evaluated.
                val =  (42 < x < function())
                val =  19 if i<12 else function()
                val =  x  or  function()

In each example, the function() may or may not be actually called, 
depending on the other values of the expression.

DaveA




More information about the Python-list mailing list