How do I check if a variable exists?

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

    I will assume that the test is going to be used in a function, similar to user97370's answer. I don't like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:

    class InitMyVariable(object):
      my_variable = None
    
    def __call__(self):
      if self.my_variable is None:
       self.my_variable = ...
    

    I don't like this, because it complicates the code and opens up questions such as, should this confirm to the Singleton programming pattern? Fortunately, Python has allowed functions to have attributes for a while, which gives us this simple solution:

    def InitMyVariable():
      if InitMyVariable.my_variable is None:
        InitMyVariable.my_variable = ...
    InitMyVariable.my_variable = None
    

提交回复
热议问题