Does Python have something like an empty string variable where you can do?:
if myString == string.empty:
Regardless what's the most elegant way to check for empty string values? I find hard coding ""
every time for checking an empty string not as good.
How about this? Perhaps it's not "the most elegant", but it seems pretty complete and clear:
Either the following
or even
Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just do this:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use
myString == ""
. See the documentation on Truth Value Testing for other values that are false in Boolean contexts.Clean code approach
Doing this:
foo == ""
is very bad practice.""
is a magical value. You should never check against magical values (more commonly known as magical numbers)What you should do is compare to a descriptive variable name.
Descriptive variable names
One may think that "empty_string" is a descriptive variable name. It isn't.
Before you go and do
empty_string = ""
and think you have a great variable name to compare to. This is not what "descriptive variable name" means.A good descriptive variable name is based on its context. You have to think about what the empty string is.
Simple form field example
You are building a form where a user can enter values. You want to check if the user wrote something or not.
A good variable name may be
not_filled_in
This makes the code very readable
Thorough CSV parsing example
You are parsing CSV files and want the empty string to be parsed as
None
(Since CSV is entirely text based, it cannot represent
None
without using predefined keywords)A good variable name may be
CSV_NONE
This makes the code easy to change and adapt if you have a new CSV file that represents
None
with another string than""
There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.
Compare this to
The first question here is, Why does the empty string deserve special treatment?
This would tell future coders that an empty string should always be considered as
None
.This is because it mixes business logic (What CSV value should be
None
) with code implementation (What are we actually comparing to)There needs to be a separation of concern between the two.
If you just use
it is not possible to difference a variable which is boolean
False
from an empty string''
:However, if you add a simple condition to your script, the difference is made:
I once wrote something similar to Bartek's answer and javascript inspired:
Test: