Testing for a Variable

Steve Holden sholden at holdenweb.com
Thu May 3 19:51:10 EDT 2001


"Brian Quinlan" <BrianQ at ActiveState.com> wrote in message
news:mailman.988930026.21050.python-list at python.org...
> > Hi;
> > How does one test to see if a variable is defined?
> > TIA,
> > BenO
>
> You could check to see if the variable is in the dictionaries returned by
> vars() and globals() but that won't always work. Probably the easiest way
to
> check is to do something like this:
>
> try:
> eval(var)

Probably not a good idea, in case var holds something like "system('rm *')".
Since you only need to be sure it can be referenced, simply use a reference,
as in:

try:
    var
except NameError:
    print "You lose"

> # Do something
> except NameError:
> # Do something else
>
no-need-to-evaluate-what-can-simply-be-referred-to-ly y'rs -- Steve





More information about the Python-list mailing list