1

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

1 Answer 1

6

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 evaluates x; if x 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.

Sign up to request clarification or add additional context in comments.

1 Comment

However, it's worth mentioning that func2() won't be even looked up if func1() returns false, so that code works even if func2 isn't defined, while the all() approach will fail with a NameError if func2 can't be found.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.