Reputation: 3519
It's common to put in a check for None or have similar error catch. Sometimes you also need another if statement that depends on x:
if x == None:
if x[0]>0:
... # some code
Can you safely combine the if statements like this (for code brevity)?
if x != None and x[0]>0:
... # some code
Or does the interpreter not guarantee the order of evaluation and stopping after the first False?
Upvotes: 1
Views: 549
Reputation: 18418
Yes, because Python and is short-circuited (wikipedia) and evaluated from left to right.
That means if x == None
, it won't evaluate the rest: Python already knows that the evaluation of the full and
is going to be False
, because:
False and True and True and True
is still False
Consider the following:
x = None
if x is not None and a != "test":
print "Point 1"
else:
print "Point 2"
The variable a
is not initialized anywhere, right? If Python hits that point, you'll get a Name Error
exception, but what you get is:
Point 2
Meaning that Python doesn't even bother evaluating the a != "test"
part.
Something similar happens with or
. If any condition is True
, Python stops evaluating:
The following code:
x = None
if x is None or a != "test":
print "Point 1"
else:
print "Point 2"
Doesn't throw an exception either, but outputs
Point 1
Bonus:
When checking if a variable is None, is much more recommended using is
(or is not
) rather than ==
or !=
(as explained in the SO question What is the difference between " is None " and " ==None ")
Upvotes: 0
Reputation: 34146
Yes it is safe, because the operators and
and or
short-circuits.
Note:
One recommendation would be to use is
if you want to check if an object is None
:
if x is not None and x[0] > 0:
# ...
Upvotes: 4