Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to rely on condition evaluation order in if statements?

Is it bad practice to use the following format when my_var can be None?

if my_var and 'something' in my_var:     #do something 

The issue is that 'something' in my_var will throw a TypeError if my_var is None.

Or should I use:

if my_var:     if 'something' in my_var:         #do something 

or

try:     if 'something' in my_var:         #do something except TypeError:     pass 

To rephrase the question, which of the above is the best practice in Python (if any)?

Alternatives are welcome!

like image 915
tgray Avatar asked Apr 15 '09 15:04

tgray


People also ask

Does the order of conditions in an if statement matter?

Yes, the order of the conditions matters. In your code, you test if(a==b) first. If all 3 integers are the same, then this will be true and only return c; will execute. It won't even bother with the rest of the conditions.

What must the condition in an if statement evaluation?

The block of code inside the if statement is executed is the condition evaluates to true. However, the code inside the curly braces is skipped if the condition evaluates to false, and the code after the if statement is executed.

How are if statements evaluated?

You always place the condition to be evaluated by JAWS between the If and Then key words. JAWS evaluates this condition to determine what statements should be performed next. When the condition is found to be true, then JAWS performs all statements following the If statement.

Are IF statements evaluated left to right?

The evaluation order is specified by the standard and is left-to-right . The left-most expression will always be evaluated first with the && clause.


2 Answers

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 ... 
like image 92
Dan Lew Avatar answered Oct 13 '22 04:10

Dan Lew


Yes it is safe, it's explicitly and very clearly defined in the language reference:

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.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

like image 20
vartec Avatar answered Oct 13 '22 04:10

vartec