How do I check if a variable exists?

后端 未结 11 1977
野的像风
野的像风 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 03:05

    To check the existence of a local variable:

    if 'myVar' in locals():
      # myVar exists.
    

    To check the existence of a global variable:

    if 'myVar' in globals():
      # myVar exists.
    

    To check if an object has an attribute:

    if hasattr(obj, 'attr_name'):
      # obj.attr_name exists.
    

提交回复
热议问题