Reputation: 1861
Is it a good practice to rely on the order of expressions when we have multiple and
statements?
More precisely, I have a string (the string could be None at times) and based on its length I want some actions. Is the following a good code?
import os
mystr = os.getenv('MYSTR_ENV_VAR')
if mystr and len(mystr)>10:
print('do sth')
else:
print('do sth else')
Note that when mystr
is None
, the code len(mystr)
will throw an error if executed. Therefore, I am relying on the if statement to first make sure mystr
is not empty or None, and then evaluate the length. This code works and if it is safe, the logic suits my needs. Is it the correct Pythonic way of doing this?
Upvotes: 1
Views: 2244
Reputation: 2169
Python evaluates boolean conditions lazily. So your code is safe as if
statement will check your string existence first.
From docs:
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.
Upvotes: 3
Reputation: 412
Check the docs for Python 3.x, the operators support short-circuiting, i.e. if the first expression fails the if
test in an and
compound test, the succeeding tests aren't evaluated
For or
This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
For and
This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
Upvotes: 0