Test to see if variable exists

Discussion in 'Python' started by lamar_air, Aug 12, 2003.

  1. lamar_air

    lamar_air Guest

    I need an if statement to test if a variable exists in a pyton script

    eg. if var1 exists:
    do this
    else:
    do this
     
    lamar_air, Aug 12, 2003
    #1
    1. Advertisements

  2. lamar_air

    John Hunter Guest

    lamar> I need an if statement to test if a variable exists in a
    lamar> pyton script eg. if var1 exists: do this else: do this --


    try: x
    except NameError:
    # x doesn't exist, do something
    else:
    # x exists, do something else
     
    John Hunter, Aug 12, 2003
    #2
    1. Advertisements

  3. If it's in a dictionary you can do this: var1.get('key','not found')

    ( just learned that all of 2 minutes ago ;] )
     
    Gabriel Cooper, Aug 12, 2003
    #3
  4. [Graham Breed]
    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
     
    =?iso-8859-1?q?Fran=E7ois_Pinard?=, Aug 12, 2003
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.