Python hasattr

Summary: in this tutorial, you’ll learn how to use the Python hasattr() function to check if an object has a named attribute.

Introduction to Python hasattr() function

The hasattr() function returns True if an object has a named attribute specified by a string:

hasattr(object, name)Code language: Python (python)

The hasattr() function has two parameters:

  • object is the object that you want to check.
  • name is a string that specifies the name of the attribute.

The hasattr() returns True if the object has an attribute with the name specified by the string name or False otherwise.

Python hasattr() function example

The following example illustrates how to use the hasattr() function:

class Message:
    error = 'error'
    warning = 'warning'
    info = 'info'
    success = 'success'


result = hasattr(Message, 'error')
print(result)  # 👉 True


result = hasattr(Message, 'information')
print(result)  # 👉 FalseCode language: Python (python)

Note that everything in Python is an object including a class. Therefore, you can pass a class to the hasattr() function.

How it works.

First, define the Message class with four class attributes:

class Message:
    error = 'error'
    warning = 'warning'
    info = 'info'
    success = 'success'Code language: Python (python)

Second, use the hasattr() to check if the Message class has the error attribute:

result = hasattr(Message, 'error')
print(result)  # 👉 TrueCode language: Python (python)

In this case, it returns True because the Message class has the error attribute.

Third, use the hasattr() to check if the Message has the information attribute:

result = hasattr(Message, 'information')
print(result)  # 👉 FalseCode language: Python (python)

In this example, the hasattr() returns False because the Message class doesn’t have the information attribute.

A practical example of Python hasattr() function

In practice, you use the hasattr() function to check if an object has an attribute or a method with the name is only known at runtime before accessing it. For example, you can use the hasattr() to check if an object has a method before calling it.

The following example enhances the Validation class from the getattr() tutorial:


import re


class Validation:
    ERRORS = {
        'required': 'The {} is required',
        'email': 'The {} is not a valid email address'
    }

    def _required(self, value):
        return len(value) > 0

    def _email(self, value):
        pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
        return re.fullmatch(pattern, value)

    def validate(self, data, rules):
        errors = {}
        for field, rule in rules.items():
            if hasattr(self, f'_{rule}'):
                is_valid_method = getattr(self, f'_{rule}')
                if not is_valid_method(data[field]):
                    errors[field] = self.ERRORS[rule].format(field)
            else:
                errors[field] = f'The rule {rule} is not supported'

        return errors


if __name__ == '__main__':
    validation = Validation()
    data = {'name': 'Jane Doe', 'email': '[email protected]'}
    rules = {'name': 'required', 'email': 'email'}
    errors = validation.validate(data, rules)
    print(errors)
Code language: Python (python)

In this example, the hasattr() checks if the Validation class has a method with a name that matches a rule before calling it. If the method doesn’t exist, the validate() method adds an entry to the errors dictionary.

Summary

  • Use Python hasattr() to check if an object has an attribute with a name.
Did you find this tutorial helpful ?