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. Advertising

  2. lamar_air

    John Hunter Guest

    >>>>> "lamar" == lamar air <> writes:

    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. Advertising

  3. lamar_air wrote:

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

    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]

    > 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
     
    =?iso-8859-1?q?Fran=E7ois_Pinard?=, Aug 12, 2003
    #4
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Adam J Knight

    Test if Session Variable Exists!!

    Adam J Knight, Feb 17, 2006, in forum: ASP .Net
    Replies:
    3
    Views:
    11,025
    Ravi Ambros Wallau
    Feb 17, 2006
  2. Totan
    Replies:
    0
    Views:
    1,030
    Totan
    Apr 17, 2006
  3. Squid Seven
    Replies:
    11
    Views:
    453
    msalters
    Jul 11, 2005
  4. Colin Summers

    test to see if a variable exists

    Colin Summers, Jun 15, 2007, in forum: Ruby
    Replies:
    4
    Views:
    191
    Morton Goldberg
    Jun 16, 2007
  5. Ivan Marsh

    Testing to see if a variable exists...

    Ivan Marsh, Nov 11, 2003, in forum: Javascript
    Replies:
    12
    Views:
    212
    Thomas 'PointedEars' Lahn
    Nov 29, 2003
Loading...

Share This Page