[Tutor] diferent between " "(empty string) and None as condition

Mats Wichmann mats at wichmann.us
Fri Apr 24 08:56:08 EDT 2020


On 4/23/20 1:06 PM, Emin Kovac wrote:
> pasword = ""
> while not pasword:
> pasword = input ('Pasword: ')
> 
> username = None
> while not username:
> username = input('Username: ')
> My question is when should I or what is better to use as
> condition empty string (" ") or None?
> Anyway, what is different between an empty string and None

not intending to sound flip: they have different types - one is a
string, and one isn't. that matters depending on the circumstances.

In general, it's really useful to have a thing that can be used when you
need to distinguish expected from unexpected - this is sometimes called
a sentinel. If a function returns a string, but it would never return an
empty string as a usable value, then you can use the empty string as the
sentinel.  But consider a function that returns a string, and they're
all valid, including the empty string: let's say it returns an
operating-system specific file suffix which should be appended to a
filename.  When called on Windows, the function returns ".exe"; when
called on Linux it returns "" - because there is in fact no suffix that
needs to be appended.  Now we need a way to distinguish between
returning that perfectly valid empty string, and failing so badly the
caller should take remidial action instead of proceeding with that value
- this is a good place to return None, because it's not a string at all,
so the caller of the function can detect the difference.


=== extra credit, no need to go here if you don't want:

There are also cases where things are coded in such a way that None is a
valid value, and can't be used as the sentinel, and you need yet another
value to distinguish that something out-of-band happened.  You can do
this by calling object() - every Python object instance has a unique
identity, and if you save off one and don't free it, nothing else during
the run of the program will have that identity so you can check against
it (using "is", which compares identity, not "==", which compares values):

BADVALUE = object()

rv = foo(some, arguments)
if rv is BADVALUE:
    # bail out here, function failed


More information about the Tutor mailing list