Python hasattr() With Examples

Python hasattr() function is used to test if the specified object has the given attribute or not. This function returns a boolean value.

Python hasattr()

Python hasattr() function syntax is:

hasattr(object, name)

object can be any object whose attribute will be checked.

name should be string and name of the attribute to be checked.

Internally this function calls getattr(object, name) and returns True. If AttributeError is thrown by getattr() function call, then False is returned. Otherwise, True is returned.

Python hasattr() example

Let’s look at an example of hasattr() function.

class Employee:
    id = 0
    def __init__(self, i, n): = i = n
d = Employee(10, 'Pankaj')
if hasattr(d, 'name'):
    print(getattr(d, 'name'))

Output: Pankaj

Python hasattr() vs in

The benefit of hasattr() function is visible when the attribute value is determined dynamically, such as getting it from user input. We can’t do the same thing with x in object because of dynamic nature.

Let’s look at another example where we will ask the user to enter the attribute value, then use hasattr() to check if it exists or not and proceed accordingly.

d = Employee(10, 'Pankaj')
attr = input('nPlease enter Employee attribute to get details:n')
if hasattr(d, attr):
    print(attr, '=', getattr(d, attr))
    print('invalid employee attribute')


Please enter Employee attribute to get details:
id = 10
# next iteration with invalid user input
Please enter Employee attribute to get details:
invalid employee attribute


Python hasattr() is a utility function to check if the attribute is present or not for the object before we try to use it in our program. We can easily implement this function or use try-expect to have this logic in our program, but using this function is recommended to have a clean code.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: