You can use the all()
builtin (which takes an iterable of expressions):
if all([condition1, condition2, ...]):
return value
The expressions will be evaluated in order (since all()
expects an iterable), so from left to right in this example with a list.
As soon as all()
encounters the first expression that evaluates to False
it will short circuit and stop pulling expressions from the iterable. If your expressions are expensive to evaluate, you can make use of this by passing it a generator instead of a pre-built sequence.
Here's a more advanced example using a generator in order to make use of the short circuiting to avoid evaluating later expressions:
def fail():
raise Exception("Boom")
def conditions():
yield 1 == 1
yield 2 == 42
yield fail()
if all(conditions()):
print "All True"
else:
print "Not all True"
So calling conditions()
will return a generator object. Iterating over that generator will cause the code in that function to run up to the first yield
statement, then evaluate the expression after that yield return the result as the first item. Then the code in the generator is paused until all()
pulls the next value, which will resume the code and run it until the next yield
statement is encountered, etc.
Therefore this will never call fail()
because after 2 == 42
will evaluate to False
and all()
will stop iterating over the generator.