Test to see if variable exists

François Pinard pinard at iro.umontreal.ca
Tue Aug 12 21:21:20 CEST 2003


[Graham Breed]

> lamar_air wrote:
> > I need an if statement to test if a variable exists in a pyton script

> locals().has_key('var1')

The above could also be written:

    'var1' in locals()

However, whenever I need to test this (the need is rather unusual), instead
of `if', I prefer writing:

    try:
       var1
    except NameError:
       pass                     # `var1' does not exist
    else:
       pass                     # `var1' exists

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard





More information about the Python-list mailing list