How do I check if a variable exists?

后端 未结 11 1936
野的像风
野的像风 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
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 02:59

    A simple way is to initialize it at first saying myVar = None

    Then later on:

    if myVar is not None:
        # Do something
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-11-22 03:06

    The use of variables that have yet to been defined or set (implicitly or explicitly) is almost always a bad thing in any language, since it often indicates that the logic of the program hasn't been thought through properly, and is likely to result in unpredictable behaviour.

    If you need to do it in Python, the following trick, which is similar to yours, will ensure that a variable has some value before use:

    try:
        myVar
    except NameError:
        myVar = None
    
    # Now you're free to use myVar without Python complaining.
    

    However, I'm still not convinced that's a good idea - in my opinion, you should try to refactor your code so that this situation does not occur.

    0 讨论(0)
提交回复
热议问题