Pythonic way to check if something exists?

Solution 1:

LBYL style, "look before you leap":

var_exists = 'var' in locals() or 'var' in globals()

EAFP style, "easier to ask forgiveness than permission":

try:
    var
except NameError:
    var_exists = False
else:
    var_exists = True

Prefer the second style (EAFP) when coding in Python, because it is generally more reliable.

Solution 2:

I think you have to be careful with your terminology, whether something exists and something evaluates to False are two different things. Assuming you want the latter, you can simply do:

if not var:
   print 'var is False'

For the former, it would be the less elegant:

try:
   var
except NameError:
   print 'var not defined'

I am going to take a leap and venture, however, that whatever is making you want to check whether a variable is defined can probably be solved in a more elegant manner.