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?
An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.
It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.
An empty string is a string instance of zero length, whereas a null string has no value at all.
Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With