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.
you could always:
try:
some_object
except NameError:
do_something()
else:
do_something_else()
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With