Pythonic way to check if something exists?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)