How to know if an object has an attribute in Python

ID : 418

viewed : 173

Tags : pythonattributespython

Top 5 Answer for How to know if an object has an attribute in Python

vote vote


Try hasattr():

if hasattr(a, 'property'): 

See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.

vote vote


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


try:     doStuff( except AttributeError:     otherStuff() 

... is preferred to:

if hasattr(a, 'property'):     doStuff( else:     otherStuff() 
vote vote


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') 
vote vote


I think what you are looking for is hasattr. However, I'd recommend something like this if you want to detect python properties-

try:     getattr(someObject, 'someProperty')          except AttributeError:     print "Doesn't exist" else     print "Exists" 

The disadvantage here is that attribute errors in the properties __get__ code are also caught.

Otherwise, do-

if hasattr(someObject, 'someProp'):     #Access someProp/ set someProp     pass 

The reason for my recommendation is that hasattr doesn't detect properties.

vote vote


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 

Top 3 video Explaining How to know if an object has an attribute in Python