None vs Empty String in Python

I have an existing application that connects to a database. It works under Python 2.7.

The application is incompatible with the way it uses None and "" to populate variables that do not matter. I want to make this consistent and try to update the code anyway.

Thinking as a database person, I think of None as the same as Null, and would suggest that it would be the right choice for empty variables, but then it causes problems when the application does things like

if variable.upper() == "X": #Do something 

Since this causes an error if the variable is of type None.

I can do

 if variable is not None and variable.upper() == "X": #Do something 

But that seems overly detailed.

Is there any best practice for how this needs to be handled?

+6
source share
3 answers

You can shorten the code a bit by simply writing

 if variable and variable.upper() == "X": #Do something 

If the variable is absent or empty, then it is equivalent to False.

+9
source

if (variable or '').upper() == 'X' or variable and variable.upper() == 'X' will be shortened, but this, of course, is not as compact as the source code. I am afraid that you will not be much better.

You could do

 def norm(s): return s or '' ... if norm(s) == 'X': 

but in the end, this also will not change. Perhaps the original difference was not so controversial at all, but rather very pragmatic in context?

+3
source
 if variable and variable.upper() == 'X' 

a little less verbose. It will also handle None and the empty string in the same way if that is what you want.

Edit: note that this has different semantics of the expression you sent as it handles empty lines ... i.e. in your expression the value is rhs and will be evaluated if the variable is an empty string, but in this expression it is not like an empty string evaluated as False

+2
source

Source: https://habr.com/ru/post/903838/


All Articles