Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: check if object exists in scope [duplicate]

Tags:

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.

like image 323
Jonathan Livni Avatar asked Jun 17 '11 08:06

Jonathan Livni


2 Answers

you could always:

try:
    some_object
except NameError:
    do_something()
else:
    do_something_else()
like image 169
Jonathan Livni Avatar answered Oct 01 '22 16:10

Jonathan Livni


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
like image 32
Michael Kent Avatar answered Oct 01 '22 18:10

Michael Kent