Testing for a Variable

Sheila King sheila at spamcop.net
Thu May 3 20:19:58 EDT 2001


On Thu, 03 May 2001 23:51:10 GMT, "Steve  Holden" <sholden at holdenweb.com>
wrote in comp.lang.python in article
<O9mI6.69314$qc2.18117812 at typhoon.southeast.rr.com>:

:> > 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"

I was also wondering, if this might have to do with the cgi stuff that Ben has
been working on. If someone is working with environment variables, or a
FieldStorage, or other dictionary-like object, one can use the .has_key()
function, like this:

if form.has_key("HTTP_REFERER"):
  # do something
else:
  # do other thing

Just in case it helps...

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/




More information about the Python-list mailing list