Search code examples
pythonif-statement

Pythonic way to check if something exists?


I was wondering if there is 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'
else:
    print 'nope it does not'

Seems like a waste if all I care about is kn

Is there a way to check if something does not exist without the else?


Solution

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

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

    LBYL style, "look before you leap":

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

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