Checking for an "undefined" variable - newbie question

Alex Martelli aleax at aleax.it
Wed Aug 6 16:39:24 CEST 2003


Damien Wyart wrote:

> * Alex Martelli <aleax at aleax.it> in comp.lang.python:
>> If you can't rule out (e.g.) None as a valid value for your variable,
>> just make a unique placeholder value such as [be sure to use a MUTABLE
>> value, else uniqueness is not guaranteed]:
> 
> Could you expand on this "uniqueness" point ? I don't see very well what
> you mean.

if you used, e.g.:

variable = 'astringthatwontactuallyoccur'

then you couldn't later test with

if variable is 'astringthatwontactuallyoccur':

because the two literals might be or not be unique so the 'is' test is
not guaranteed to work -- you'd have to use == which is slower -- AND
again because of non-uniqueness you might be in trouble is some code did
want to assign to variable such a string, e.g. because it can get read
from a file, or interactively from the user, or otherwise constructed.

The 'is' test checks for object identity, not value, so it's faster --
and using a unique mutable object (e.g. a class) made just for the
purpose also guarantees no clashes with any actual value you might 
want to assign to your variable.  I started that classname with an
underscore to signify it's meant for internal use in the module, not
for export to other modules, by the way.


Alex








More information about the Python-list mailing list