How do I check if a variable exists?

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

提交回复
热议问题