Pythonic way to check if something exists?


This is pretty basic but I was coding and started wondering if there was a pythonic way to check if something does not exist. Here's how I do it if its true:

var = 1
if var:
    print 'it exists'

but when I check if something does not exist, I often do something like this:

var = 2
if var:
    print 'it exists'
    print 'nope it does not'

Seems like a waste if all I care about is knIs there a way to check if something does not exist without the else?

This question is tagged with python if-statement

~ Asked on 2012-02-22 06:29:29

The Best Answer is


LBYL style, "look before you leap":

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

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

except NameError:
    var_exists = False
    var_exists = True

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

~ Answered on 2012-02-22 06:40:07


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:

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.

~ Answered on 2012-02-22 06:32:02

Most Viewed Questions: