I've mentioned before that
empty strings in Python are false.
This leads to a common if not string
paradigm. Unfortunately, this can be
problematic. Check out this snippet:
>>> string = ""
>>> if not string:
... print("empty")
...
empty
That pretty much worked out just as we imagined. The empty string returned False
and our code did what it was supposed to. When we start running into a problem is
when our string isn't really a string. For example:
>>> string = None
>>> if not string:
... print("empty")
...
empty
In this case, our string is now a None object. We may have done this on purpose
or it could have been a mistake. A common scenario is that a function returned a
None
object when we expected a string. What we find is that None
, False
,
0
, and "" are all equivalent, and in the paradigm of checking for an empty
string with if not string
, empty.
For quick and dirty scripts, if not string
works just fine. Small bits of code
where you know exactly what the input is going to look like or one-off scripts
that need some basic error-checking are not usually an issue. For more complicated
code, the answer is better error-checking before getting to if not string
. For
example, if a function can return a None object for some reason, that's a condition
that should be checked for when the function returns. In
my
experience,
you can expect to run into this often when working with third-party APIs.