Checking for an "undefined" variable - newbie question

Michael Chermside mcherm at mcherm.com
Wed Aug 6 15:04:19 CEST 2003


> How do I check if a variable has been defined??
> 
> The following don't appear to work:
> 
> if variable:
> 
> if variable is None:
> 
> 
> I have only one (ugly) solution:
> 
> try:
>      variable
> except NameError:
>      ...
> 
> which works, but is a bit clumsy if I just want to know if the thing already 
> exists.
> 
> If there's a more elegant way to check this, that would be great!

Daniel: For a newbie, you're doing GREAT! You have already
correctly determined the best way to test if a variable exists.
There IS an alternative... you can get ahold of the namespace as
a dict, then see if the name is a key. Something like this:

>>> g = globals()
>>> print g.has_key('x')
False
>>> x = 7
>>> print g.has_key('x')
True
>>>

...except that depending on where you write this you might
want locals() instead of globals(). However, your solution
testing for the exception is just as good.

You might ask, "If Python is such a nice language, how come
it's so difficult to test whether a variable is defined?" In
fact, the reason is that programs written in a pythonic style
rarely ever need such a test. In some languages it is 
idiomatic to leave a variable undefined and use that as a 
"special value". But in Python, it is more idiomatic to go
ahead and assign SOME value to the variable, then use "None"
for the "special value" indicating there is no meaningful
normal value.

There are a couple of reasons for this practice. One is that
variables in Python can refer to objects of any type, so
even if "x" is NORMALLY an int, it can also be assigned to
be None (or any other "special value") without a type mismatch
syntax error. Another reason is that it's awefully convenient
to test for None... with most object types, all values are
considered "True", so just saying:

    if x:
        ...

will execute the code when x has a value, and skip it if x is
None. (Of course, if some other non-true values are allowed, 
like 0 or "", then you may need "if x is None" instead.) And
lastly, its a bit of a pain to test for leaving a variable
undefined, so it's easier to use None as the "special value".

-- Michael Chermside






More information about the Python-list mailing list