if cpu_expensive_condition() or simple_condition():
do_something()
out of two condition in OR statement in above python code which will be evaluate first ? , and is it compulsory that both will be evaluate ?
if cpu_expensive_condition() or simple_condition():
do_something()
out of two condition in OR statement in above python code which will be evaluate first ? , and is it compulsory that both will be evaluate ?
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.
Quoted from Python Language Reference
Python evaluates from left to right, and both sides do not need to be evaluated. Consider the following example.
def left(x):
print 'left'
return x
def right(x):
print 'right'
return x
if left(False) or right(False):
print 'Done'
if left(True) or right(True):
print 'Done'
This will produce the following output:
left
right #This is where the first if statement ends.
left
Done #Only the left side was evaluated
According to Boolean Operations — and, or, not in the Python documentation:
This is a short-circuit operator, so it only evaluates the second argument if the first one is False.
So cpu_expensive_condition()
will always be evaluated. simple_condition()
will only be evaluated when cpu_expensive_condition()
returns False
(or something that evaluates to False
, such as 0
or ''
or None
).
See also: Does Python support short-circuiting?
Python does short-circuit evaluation. Of course the first statement will be evaluated first. The second will only be evaluated if the first is False
or false-ish.