Is it safe to rely on condition evaluation order in if statements?
Solution 1:
It's safe to depend on the order of conditionals (Python reference here), specifically because of the problem you point out - it's very useful to be able to short-circuit evaluation that could cause problems in a string of conditionals.
This sort of code pops up in most languages:
IF exists(variable) AND variable.doSomething()
THEN ...
Solution 2:
Yes it is safe, it's explicitly and very clearly defined in the language reference:
The expression
x and y
first evaluatesx
; ifx
isfalse
, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.