10.6. Reflection Hasattr

  • Check if object has attribute

  • There is no __hasattr__() method

  • Calling hasattr(obj, attrname)

  • Will call __getattribute__() and checks if raises AttributeError

  • If no exception, then return True

  • If exception, then call __getattr__() and check

  • If __getattr__() succeeds then return True

  • If __getattr__() fail then return False

10.6.1. Example

>>> class Point:
...     x: int
...     y: int
...     z: int
>>> pt = Point()
>>> pt.x = 1
>>> pt.y = 2
>>> hasattr(pt, 'x')
True
>>>
>>> hasattr(pt, 'y')
True
>>>
>>> hasattr(pt, 'z')
False
>>>
>>> hasattr(pt, 'other')
False