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

6

5

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...:/ )

Bastion answered 3/6, 2011 at 17:45 Comment(0)
A
10

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.

Atropos answered 3/6, 2011 at 17:47 Comment(3)
The first answer, and naming the behavior as short-circuiting is exactly what I was looking for. en.wikipedia.org/wiki/Short-circuit_evaluation Thanks! And here is the PEP about it: python.org/dev/peps/pep-0308Bastion
@Somebody still uses you MS-DOS Any time.Atropos
@Somebody still uses you MS-DOS +1 for the link to the PEP.Atropos
D
2

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.

Dahna answered 3/6, 2011 at 17:49 Comment(0)
D
2

If var is False, evaluation stops.

See the Short-Circuit Behavior section in PEP 308.

Dignadignified answered 3/6, 2011 at 17:51 Comment(0)
P
1

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
Patch answered 3/6, 2011 at 17:49 Comment(0)
P
1

The Python documentation says that and and or are short-circuiting, so no, var2 == getSomeValue() won't be evaluated if var is false.

Puga answered 4/6, 2011 at 8:33 Comment(0)
A
1

Re "I didn't know what to search"

You don't need to search when there's an index available:

Browse to the Python home page. Successively click on

  • DOCUMENTATION
  • Current Docs
  • index (it's in the top right corner)
  • A

Scroll down until you see

and
    bitwise
    operator

You don't want bitwise, click on operator.

If you are on Windows, you have the manuals on your computer, with a nice-enough GUI interface. Check out the Contents / Index / Search / Favorites panes near the top left corner.

Ainsworth answered 4/6, 2011 at 9:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.