How do I check if a variable exists?

后端 未结 11 2104
野的像风
野的像风 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:57

    I created a custom function.

    def exists(var):
         return var in globals()
    

    Then the call the function like follows replacing variable_name with the variable you want to check:

    exists("variable_name")
    

    Will return True or False

提交回复
热议问题