Python hasattr() Function

A useful built in function in Python is hasattr(). This function is used to test if an object has some attribute. hasattr() returns True if the object you specify contains a particular attribute and False if it does not.

hasattr() syntax:

hasattr(object, attribute)

hasattr() takes two parameters:

  • object. The object whose attribute you want to check
  • attribute. A string that contains the name of the attribute you’re searching for

The code example below shows how to use hasattr().

class Event:
    def __init__(self, name, location):
        self.name = name
        self.location = location

wedding = Event("Vuyisile's Wedding", "Madagascar")
hasattr(wedding, "name")

In the example above, hasattr() would return True since the Event class has a “name” attribute. To get the value of the attribute, use getattr():

>>> getattr(wedding, "location")
"Madagascar"