None vs Empty String in Python

George picture George · Dec 15, 2011 · Viewed 31.2k times · Source

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?

Answer

obmarg picture obmarg · Dec 15, 2011

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.