How do I check if a variable exists?


Question

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?

1
804
9/12/2016 4:40:47 PM

Accepted Answer

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.
1396
5/9/2009 1:16:05 PM

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

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 still don't think that's a good idea - in my opinion, you should refactor your code so that this situation does not occur.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon