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' else: 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?
To check if a local variable exists in Python, use in operator and check inside the locals() dictionary. To check if a global variable exists in Python, use in operator and check inside the globals() dict. To check if an object has an attribute, use the hasattr() function.
“not in” operator − This operator is used to check whether an element is not present in the passed list or not. Returns true if the element is not present in the list otherwise returns false.
Python hasattr() method Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With