How do I check if a variable exists?

Max Frai picture Max Frai · May 9, 2009 · Viewed 1.1M times · Source

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?

Answer

Ayman Hourieh picture Ayman Hourieh · May 9, 2009

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.