Pythonic way to check if something exists?

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.


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.


To check if a var has been defined:

var = 2

try: 
    varz
except NameError:
    print("No varz")

To check if it is None / False

if varz is None

...or

if not varz