How do I check if a variable exists?

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

    Using try/except is the best way to test for a variable's existence. But there's almost certainly a better way of doing whatever it is you're doing than setting/testing global variables.

    For example, if you want to initialize a module-level variable the first time you call some function, you're better off with code something like this:

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

提交回复
热议问题