Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if var and var2 == getSomeValue()" in python - if the first is false, is the second statement evaluated?'

I have some code like this:

if var:
    if var2 == getSomeValue()

This could be in a single expression.

if var and var2 == getSomeValue():

...but getSomeValue() can only be called if var is True.

So, when calling if var and var2 == getSomeValue(), are both evaluated by the interpreter, or the evaluation stops at var if False? Where I can find this information on python documentation? (I didn't know what to search...:/ )

like image 327
Somebody still uses you MS-DOS Avatar asked Jun 03 '11 17:06

Somebody still uses you MS-DOS


4 Answers

This is called short-circuiting, and Python does it, so you're good.

UPDATE: Here's a quick example.

>>> def foo():
...     print "Yay!"
... 
>>> if True and foo() is None:
...     print "indeed"
... 
Yay!
indeed
>>> if False and foo() is None:
...     print "nope"
... 

UPDATE 2: Putting the relevant PEP (308) in my answer so it doesn't get overlooked in the excellent comment from @Somebody still uses you MS-DOS.

like image 111
Hank Gay Avatar answered Oct 19 '22 18:10

Hank Gay


The second item isn't evaluated - you could verify this with a simple program:

def boo():
  print "hi"
  return True

a = False
b = True

if a and b == boo():
  print "hi2"

Running it produces no output, so you can see that boo() is never called.

like image 28
Chris Bunch Avatar answered Oct 19 '22 18:10

Chris Bunch


If var is False, evaluation stops.

See the Short-Circuit Behavior section in PEP 308.

like image 2
Gregg Avatar answered Oct 19 '22 17:10

Gregg


The evaluation getSomeValue won't be evaluated:

var = False
if var and foo():
   print "here"
else:
   print "there"

def foo():
   print "In foo"
   return False
like image 1
carlosfigueira Avatar answered Oct 19 '22 17:10

carlosfigueira