Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' 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?

like image 956
Lostsoul Avatar asked Feb 22 '12 06:02

Lostsoul


People also ask

How do you check if something exists in Python?

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.

How do you check if an item is not in a list Python?

“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.

How do you check if an object has a method Python?

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.


1 Answers

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.

like image 176
wim Avatar answered Sep 20 '22 22:09

wim