Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>
EDIT:This approach has serious limitation. It should work if the object is an iterable one. Please check the comments below.
If you are using Python 3.6 or higher like me there is a convenient alternative to check whether an object has a particular attribute:
if 'attr1' in obj1:
print("attr1 = {}".format(obj1["attr1"]))
However, I'm not sure which is the best approach right now. using hasattr()
, using getattr()
or using in
. Comments are welcome.