109

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?

3
  • 1
    There's always ternary: stackoverflow.com/questions/394809/python-ternary-operator :) ... thought it might not be the most Pythonic way to write it out. Commented Feb 22, 2012 at 6:32
  • 8
    If var doesn't actually exist, then you are going to get an exception raised when you try to use it. That is outside of what if/else can handle. if var assumes that var exists, and tests if it is "true-ish" (becomes True rather than False if converted to boolean). Commented Feb 22, 2012 at 8:56
  • 1
    You are not checking the existence of a variable, but checking if it's value is Trueas a boolean context. Commented Jul 19, 2013 at 10:02

7 Answers 7

224

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Test if var does not exist: 'var' not in locals() and 'var' not in globals()
This LBYL solution has a fundamental flaw: nonlocals (names in an outer function scope) aren't included in locals() unless they're referenced in the inner function scope. gist
46

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.

2 Comments

sorry didn't mean false. meant if it does not exist. I use it more often in sql queries(I wrap an if statement in a select query and if no result comes back then I do some work), so not false looking for not existing.
well config = config() and then if not config: gives me "local variable config referenced before assigment" :)
8

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 .

2 Comments

Simplest of all the solutions
This doesn't work for a dictionary.
6

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

Comments

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

1 Comment

This will not handle the case where the variable was never defined, which is OP's question.
3

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'

Comments

-1

Quite often I find that the situations where I want to do one thing if a variable exists or do something else if a variable doesn't exist are situations where I want a function anyway. So you might want to call a function that will behave in one way if a variable exists or another way if it doesn't. In this case you can set the default value of the variable to None so that the function behaves in one way if you call it with the variable or behaves in a different way if you call it without it:

def myfunc(var = None):
    if var:
        print(var)
    else:
        print('Var does not exist')

1 Comment

This is a decent idea, but if var is too broad: it'll treat None the same as 0 or False or '' (the empty string) or even [] (an empty list). What you want is if var is None. Even then, you might want to let the user pass in None explicitly, but that's another can of worms: you'd need a sentinel object then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.