Does Python evaluate if's conditions lazily?

PythonLazy Evaluation

Python Problem Overview


For example, if I have the following statement:

if( foo1 or foo2)
    ...
    ...

if foo1 is true, will python check the condition of foo2?

Python Solutions


Solution 1 - Python

Yes, Python evaluates boolean conditions lazily.

The docs say,

> The expression x and y first evaluates x; if x is false, its value is > returned; otherwise, y is evaluated and the resulting value is > returned. > > The expression x or y first evaluates x; if x is true, its value is > returned; otherwise, y is evaluated and the resulting value is > returned.

Solution 2 - Python

and or is lazy

& | is not lazy

Solution 3 - Python

Python's laziness can be proved by the following code:

def foo():
    print('foo')
    return False

def bar():
    print('bar')
    return False

foo() and bar()         #Only 'foo' is printed

On the other hand,

foo() or bar()

would cause both 'foo' and 'bar' to be printed.

Solution 4 - Python

This isn't technically lazy evaluation, it's short-circuit boolean expressions.

Lazy evaluation has a somewhat different connotation. For example, true lazy evaluation would likely allow this

def foo(arg) :
    print "Couldn't care less"

foo([][0])

But Python doesn't.

Python is also nice in that it "echos" it's boolean arguments. For example, an or condition returns either it's first "truthy" argument or the last argument (if all arguments are "falsey"). An and condition does the inverse.

So "echo argument" booleans means

> 2 and [] and 1

evaluates to [], and

> [] or 1 or 2

evaluates to 1

Solution 5 - Python

A short demo would be to compare the time difference between

all(xrange(1,1000000000))

and

any(xrange(1,1000000000))

The all() has to check every single value, whilst the any() can give up after the first True has been found. The xrange, being a generator, therefore also gives up generating things as soon as the evaluator is done. For this reason, the all will consume large amounts of RAM and take ages, whilst the any will use just a few bytes and return instantaneously.

Solution 6 - Python

Yes, Python evaluates lazily, so foo2 will not be checked.

I use this all the time for grabbing items from dictionary-like objects if I don't know if the key exists:

if 'key' in mydict and mydict['key'] == 'heyyo!':
    do_stuff()

See @unutbu's answer for a fuller explanation.

Solution 7 - Python

It is really the or part that is short circuited:

>>> 1 or 1/0  #also 0 and 1/0
1
>>> 0 or 1/0  #also 1 and 1/0

Traceback (most recent call last):
  File "<pyshell#1240>", line 1, in <module>
    0 or 1/0
ZeroDivisionError: integer division or modulo by zero

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionogama8View Question on Stackoverflow
Solution 1 - PythonunutbuView Answer on Stackoverflow
Solution 2 - PythonEric WangView Answer on Stackoverflow
Solution 3 - PythonErik VelosoView Answer on Stackoverflow
Solution 4 - PythonPete CacioppiView Answer on Stackoverflow
Solution 5 - PythonJ.JView Answer on Stackoverflow
Solution 6 - PythonjdotjdotView Answer on Stackoverflow
Solution 7 - PythondansalmoView Answer on Stackoverflow