26

Possible Duplicate:
Python - checking variable existing

Is there an efficient, simple and pythonic way to check if an object exists in the scope?

In Python everything's an object (variables, functions, classes, class instances etc), so I'm looking for a generic existence test for an object, no matter what it is.

I half expected there to be an exists() built-in function, but I couldn't find any to fit the bill.

Community
  • 1
  • 1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

5 Answers5

40

you could always:

try:
    some_object
except NameError:
    do_something()
else:
    do_something_else()
phihag
  • 278,196
  • 72
  • 453
  • 469
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
30

You seem to be searching for hasattr(). You use it to see if, in the scope of the namespace of an object (and even imported modules are objects), a given attribute name exists.

So, I can do:

>>> import math
>>> hasattr(math, 'atan')
True

or something like:

>>> class MyClass(object):
...     def __init__(self):
...         self.hello = None
... 
>>> myObj = MyClass()
>>> hasattr(myObj, 'hello')
True
>>> hasattr(myObj, 'goodbye')
False
Michael Kent
  • 1,736
  • 12
  • 11
  • Hah. There's no answer talking about hasattr, so I craft one, making sure my examples work correctly, then post it, and POW! @Dog-eat-cat-world has beat me to it. – Michael Kent Jun 17 '11 at 13:33
8

I believe you're looking for something like locals. Here's how it works:

>>> foo = 1
>>> l = locals()
>>> print l
{'__builtins__': <module '__builtin__' (built-in)>, 'l': {...}, 
 '__package__': None,'__name__':'__main__', 'foo': 1, '__doc__': None}
>>> print l['foo']
1
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • You'll need to call locals to update the locals dictionary each time you want to check for existence, my guess would be that this is less efficient than the try-except method, although a benchmark is in order – Jonathan Livni Jun 17 '11 at 09:06
  • 2
    it is better to use l.has_key('foo') for checking the existancy – prgbenz Jun 17 '11 at 10:42
  • The sequence of lookups that Python normally does for a name is `locals()`, `globals()`, and `vars(__builtin__)` -- so this is *not* checking to see if a name is currently in scope. – martineau Jun 17 '11 at 11:40
  • Just to clarify, to use `locals()` to find whether or not a variable exists you can do this: `'variable_name' in locals()`. it returns a boolean value indicating the variable's existance in the local namespace – Samie Bencherif Nov 02 '13 at 23:25
5

There will be a difference whether you are trying to determine if a local or a attribute of an object exists. For an object, hasattr(object, "attribute") will do the trick.

This also work on modules:

import math
hasattr(math,"pow") => True

But for what we can call the main scope, you will have to use locals(), as hasattr() need some sort of object to dig into. In this case there is none...

exists_mainscope = lambda name: locals().has_key(name)
exists_mainscope("test") => False

So, what you are looking for might be the following:

def exists(name,obj=None):
 if obj is None: return locals().has_key(name)
 else: return hasattr(obj,name)

enter code here
1

It's possible to write your own:

import __builtin__
import sys

def exists(name):
    return (name in sys._getframe(1).f_locals  # caller's locals
         or name in sys._getframe(1).f_globals # caller's globals
         or name in vars(__builtin__)          # built-in
    )

if __name__=='__main__':
    def foobar():
        local_var = 42
        print 'exists("global_var"):', exists("global_var")
        print 'exists("local_var"):', exists("local_var")

    print 'exists("baz"):', exists("baz")  # undefined
    print 'exists("dict"):', exists("dict")  # built-in
    foobar()  # global_var doesn't exist yet
    global_var = 'I think, therefore I am'
    print 'exists("global_var"):', exists("global_var")
    foobar()  # now global_var exists
martineau
  • 119,623
  • 25
  • 170
  • 301