How do I check if a variable exists?

后端 未结 11 1991
野的像风
野的像风 2020-11-22 02:09

I want to check if a variable exists. Now I\'m doing something like this:

try:
   myVar
except NameError:
   # Do something.

Are there othe

11条回答
  •  伪装坚强ぢ
    2020-11-22 02:54

    A way that often works well for handling this kind of situation is to not explicitly check if the variable exists but just go ahead and wrap the first usage of the possibly non-existing variable in a try/except NameError:

    # Search for entry.
    for x in y:
      if x == 3:
        found = x
    
    # Work with found entry.
    try:
      print('Found: {0}'.format(found))
    except NameError:
      print('Not found')
    else:
      # Handle rest of Found case here
      ...
    

提交回复
热议问题