Reputation: 1054
I have an existing application which connects to a database. It is running under Python 2.7.
The application is inconsistent in the way it uses None and "" to populate variables which do not have a value. I want to make this consistent and try to update the code to one way or the other.
Thinking as a database person I think of None as the same as Null and would assume that would be the correct choice for empty variables but then this causes problems when the application does things like
if variable.upper() == "X":
#Do something
As this raises an error if the variable is None type.
I can do
if variable is not None and variable.upper() == "X":
#Do something
But this seems unnecessarily verbose.
Is there a best practice for how this should be handled?
Upvotes: 18
Views: 52816
Reputation: 41
For those who want to distinguish None
from the empty string (''
), use str
def is_empty_string(value):
... return str(value) == ''
...
is_empty_string(None)
False
is_empty_string(0)
False
is_empty_string(' ')
False
is_empty_string('')
True
Upvotes: 4
Reputation: 46607
if (variable or '').upper() == 'X'
or variable and variable.upper() == 'X'
would both be a shorthand, but it's certainly not exactly as compact as the original code. I fear you won't get much better, though.
You could do
def norm(s):
return s or ''
...
if norm(s) == 'X':
but ultimatively it won't change to much also. Perhaps the original distinction was not so inconsistent at all, but rather very pragmatic in the context?
Upvotes: 4
Reputation: 1908
if variable and variable.upper() == 'X'
is a little less wordy. It will also treat None and the empty string in the same way if that is something you want
Edit: Note that this does have different semantics to the expression you posted in the way it handles empty strings... i.e. in your expression the rhs of the and would get evaluated if variable is the empty string, but in this expression it would not as the empty string evaluates to False
Upvotes: 4
Reputation: 9559
You could cut down on code slightly by just writing
if variable and variable.upper() == "X":
#Do something
If the variable is none or empty, then it's equivalent to False.
Upvotes: 17