Reputation: 7657
Is there any functional difference between the following two blocks of code? I'm concerned mainly with the order in which the functions are called. Are functions executed sequentially in the first if
statement?
First,
if func1() and func2() and func3() and func4():
do stuff
Second,
if func1():
if func2():
if func3():
if func4():
do stuff
Upvotes: 1
Views: 125
Reputation: 1121924
Yes, Python evaluates expressions from left to right. The functions will be called in the same order. From the reference documentation:
Python evaluates expressions from left to right.
Moreover, func2()
will not be called if func1()
returned a false value, both when using and
and when nesting if
expressions. Quoting the boolean operations documentation:
The expression
x and y
first evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
Because in the expression func1() and func2()
, func2()
will not be evaluated if func1()
returned a false value, func2()
is not called at all.
You could use a third alternative here using the all()
function:
functions = (func1, func2, func3, func4)
if all(f() for f in functions):
which would again only call functions as long as the preceding function returned a true value and call the functions in order.
The all()
approach does require that func1
, func2
, func3
, and func4
are all actually defined before you call all()
, while the nested if
or and
expression approaches only require functions to be defined as long as the preceding function returned a true value.
Upvotes: 6