Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>
Depending on the situation you can check with isinstance
what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).
One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr
might then lead to strange errors.
One nice example is the distinction between iterators and iterables (see this question). The __iter__
methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr
is useless, but isinstance
together with ABC's provides a clean solution.
However, I agree that in most situations the hasattr
approach (described in other answers) is the most appropriate solution.
According to pydoc, hasattr(obj, prop) simply calls getattr(obj, prop) and catches exceptions. So, it is just as valid to wrap the attribute access with a try statement and catch AttributeError as it is to use hasattr() beforehand.
a = SomeClass()
try:
return a.fake_prop
except AttributeError:
return default_value
As Jarret Hardie answered, hasattr
will do the trick. I would like to add, though, that many in the Python community recommend a strategy of "easier to ask for forgiveness than permission" (EAFP) rather than "look before you leap" (LBYL). See these references:
EAFP vs LBYL (was Re: A little disappointed so far)
EAFP vs. LBYL @Code Like a Pythonista: Idiomatic Python
ie:
try:
doStuff(a.property)
except AttributeError:
otherStuff()
... is preferred to:
if hasattr(a, 'property'):
doStuff(a.property)
else:
otherStuff()
This is super simple, just use dir(
object)
This will return a list of every available function and attribute of the object.
I would like to suggest avoid this:
try:
doStuff(a.property)
except AttributeError:
otherStuff()
The user @jpalecek mentioned it: If an AttributeError
occurs inside doStuff()
, you are lost.
Maybe this approach is better:
try:
val = a.property
except AttributeError:
otherStuff()
else:
doStuff(val)
You can use hasattr()
or catch AttributeError
, but if you really just want the value of the attribute with a default if it isn't there, the best option is just to use getattr():
getattr(a, 'property', 'default value')