Pythonic way to check if something exists?
Question:
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?
Answers:
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:
try:
var
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.
What about the negation?
if not var:
print 'nope it does not'
Though this is to see if the var is false / none and would blow up if var is not defined.
To see if var is defined:
try:
var
except NameError:
print 'not defined'
if not var:
#Var is None/False/0/
if var:
#Var is other then 'None/False/0'
in Python if varibale is having any value from None/False/0 then If var
condition will fail…
and for other objects it will call __nonzero__
pythonic method which may return True
or False
depending on its functionality.
To check if a var has been defined:
var = 2
try:
var
except NameError:
print("No var")
To check if it is None/False
if var is None
…or
if not var
If this is a dictionary, you can have
mydict['ggg'] = '' // doesn't matter if it is empty value or not.
if mydict.has_key('ggg'):
print "OH GEESH"
However, has_key()
is completely removed from Python 3.x, therefore, the Python way is to use in
'ggg' in mydict # this is it!
# True if it exists
# False if it doesn't
You can use in
for tuple, list, and set as well.
Of course, if the variable hasn’t been defined, you will have to raise an exception silently (just raise any exception… let it pass), if exception is not what you want to see (which is useful for many applications, you just need to log the exception.)
It is always safe to define a variable before you use it (you will run into “assignment before local reference” which means ” var is not in the scope ” in plain English). If you do something with query, the chance is, you will want to have a dictionary, and checking whether a key exists or not, use in
.
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.
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?
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:
try:
var
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.
What about the negation?
if not var:
print 'nope it does not'
Though this is to see if the var is false / none and would blow up if var is not defined.
To see if var is defined:
try:
var
except NameError:
print 'not defined'
if not var:
#Var is None/False/0/
if var:
#Var is other then 'None/False/0'
in Python if varibale is having any value from None/False/0 then If var
condition will fail…
and for other objects it will call __nonzero__
pythonic method which may return True
or False
depending on its functionality.
To check if a var has been defined:
var = 2
try:
var
except NameError:
print("No var")
To check if it is None/False
if var is None
…or
if not var
If this is a dictionary, you can have
mydict['ggg'] = '' // doesn't matter if it is empty value or not.
if mydict.has_key('ggg'):
print "OH GEESH"
However, has_key()
is completely removed from Python 3.x, therefore, the Python way is to use in
'ggg' in mydict # this is it!
# True if it exists
# False if it doesn't
You can use in
for tuple, list, and set as well.
Of course, if the variable hasn’t been defined, you will have to raise an exception silently (just raise any exception… let it pass), if exception is not what you want to see (which is useful for many applications, you just need to log the exception.)
It is always safe to define a variable before you use it (you will run into “assignment before local reference” which means ” var is not in the scope ” in plain English). If you do something with query, the chance is, you will want to have a dictionary, and checking whether a key exists or not, use in
.
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.