Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>
hasattr()
is the right answer. What I want to add is that hasattr()
can also be used well in conjunction with assert (to avoid unnecessary if
statements and make the code more readable):
assert hasattr(a, 'property'), 'object lacks property'
As stated in another answer on SO: Asserts should be used to test conditions that should never happen. The purpose is to crash early in the case of a corrupt program state.