Check for existence?
Alex Martelli
aleaxit at yahoo.com
Tue May 29 07:17:45 EDT 2001
"Gerrie Roos" <gerrie at trispen.com> wrote in message
news:3B13718D.557CDBE3 at trispen.com...
> I'm very new to Python and got a very basic question:
>
> How do I check to see if a variable exists/is available in the current
> namespace?
There are several ways to do this (I don't know if you NEED
any of those, and I doubt you do, but, just in case...).
Simplest, as already suggested, is just go ahead and try
to use the variable, but do it in a try-block:
try:
usethe(variable)
except NameError:
# can't use the variable, so, use something else!
usethe(23)
A direct check can be performed by taking advantage of the
fact that vars() returns a dictionary of all the bound
variables, and dictionaries support .has_key()...:
if vars().has_key('variable'):
usethe(variable)
else:
# can't use the variable, so, use something else!
usethe(23)
You presumably know, by inspection of your code, if the
variable you're interested in is (assuming it exists)
global or local. So, you could use locals() or else
globals() instead of vars() here.
Nobody's going to change your locals() from the outside,
actually: unless you play strange tricks with exec (or
execfile, or subtler things yet), code inspection rather
than running the code is generally best to determine if
the variable exists and is bound as a local variable of
your function. If you can't tell easily from such an
inspection, a little bit of restructuring is advised:
def f(ploop):
if haltingProblem(ploop):
variable = 23
if vars().has_key('variable'):
usethe(variable)
else:
usethe(42)
is MUCH better expressed as:
def f(ploop):
if haltingProblem(ploop):
variable = 23
else:
variable = 42
usethe(variable)
It's HIGHLY unlikely, but not 100% impossible, that
somebody could be playing tricks from the outside with
your *GLOBAL* variables, i.e., the attributes of your
module-object. I strongly suggest rearchitecting any
system based on such tricks, but if you don't have
that option, then maybe testing if a global variable
(attribute of your module object) is still there or
not MAY be the least of evils (a try/except, I'd say).
If the "variable" you mention is not really a variable
but rather some object's attribute, then the function
you want is probably hasattr(obj,'attribute_name'). You
may look into getattr() (with either try/except, or a
third argument to use as the default), too. Or, the
try/except approach can work here, too.
Alex
More information about the Python-list
mailing list