How do I check if a variable exists?
I want to check if a variable exists. Now I'm doing something like this:
try: myVar except NameError: # Do something.
Are there other ways without exceptions?
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.
Read more... Read less...
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.
A simple way is to initialize it at first saying
myVar = None
Then later on:
if myVar is not None: # Do something
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 = ...
for objects/modules, you can also
'var' in dir(obj)
>>> class Something(object): ... pass ... >>> c = Something() >>> c.a = 1 >>> 'a' in dir(c) True >>> 'b' in dir(c) False
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