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
name=""
def __init__(self, i, n):
self.id = i
self.name = 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))
else:
print('invalid employee attribute')
Output:
Please enter Employee attribute to get details:
id
id = 10
# next iteration with invalid user input
Please enter Employee attribute to get details:
i
invalid employee attribute
Summary
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.
Reference: Official Documentation