The Python Oracle

Does Python evaluate if's conditions lazily?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Does Python Evaluate If'S Conditions Lazily?
00:12 Accepted Answer Score 115
00:40 Answer 2 Score 7
01:28 Answer 3 Score 25
01:46 Answer 4 Score 77
01:54 Thank you

--

Full question
https://stackoverflow.com/questions/1396...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #lazyevaluation

#avk47



ACCEPTED ANSWER

Score 115


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.




ANSWER 2

Score 77


and or is lazy

& | is not lazy




ANSWER 3

Score 25


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.




ANSWER 4

Score 7


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