Search code examples
pythonpython-2.7boolean-expressionshort-circuiting

order of evaluation of boolean expression in python


I have a multi-part boolean expression in a piece of python code, part of which involves a call to a random number generator and evaluating an expoenential of a sum of a 2d array. Since this is buried deep in nested loops I want to avoid checking that last part if at all possible, since it's computationally expensive.

if self.B == 0 or (np.sign(self.B) == -sign) or (np.random.rand() < np.exp(-2*sign*self.B*np.sum(cluster))):
    do stuff

If either of the first two expression are true, will the random number generator still be called? Or is it guaranteed to evaluate those parts in order and stop once it finds one that is true?

I can always make it explicit by breaking it up, but it seems like something I should probably know anyway.


Solution

  • In if A or B, B is only evaluated if A is false.

    This concept is called short circuiting, and you can read a little about it here.

    The idea is that you go from left to right until a result is determined. Once that's the case, you stop.