[Tutor] does a variable exist?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 5 Mar 2002 11:09:32 -0800 (PST)


On Tue, 5 Mar 2002, Henry Porter wrote:

> I want to see if a variable exists in my program.  The variable is
> getting set within an 'if' statement, so sometimes it exists
> afterwards, but not always.  Is there a way to check for this besides
> just initializing it to something at the top of the program?

It's usually safer to initialize it at the top with a special value that
you can say means "not yet defined".

Many programmers use the 'None' value for this.  You can then check to
see, after all your tests, if that variables still has the value of
'None'.  In technical terms, we're playing with a "sentinel" value, a
value that's used mostly for it's placeholder qualities.

Without the initializtion, we force ourselves to follow the program flow
to see which variables are available to us.  I think that's just a
NameError landmine just waiting to happen.  *grin*


Alternatively, if we stuff names and values within a dictionary, we can
use the has_key() method to see if there's a certain value that hasn't
been stuffed yet:

###
>>> brothers = { 'larry' : 1,
...              'curly' : 1,
...              'moe' : 1,
...              'Chico': 2 }
>>> brothers.has_key('moe')
1
>>> brothers.has_key('Flipper')
###

so perhaps a dictionary might be what you're looking for.


Good luck!