Python

Python Hasattr()

Python is a high-level, advanced, English language like syntax, easy to learn programming language. It has various types of functions, methods, mostly built-in while some can be designed on runtime. The hasattr() is a python’s built-in utility function abbreviated as ‘has an attribute.’ It can be used with user-defined classes. It determines whether or not an object has a specific attribute. For example, it returns true if a certain object has the specified attribute, while it returns false if it does not have a specified object. The syntax of hasattr() is hasattr(object,attribute).

The hasattr() is the function itself, ‘object’ refers to the required object, ‘attribute’ refers to the name of the specified attribute that needs to be checked. If the ‘object’ has the ‘attribute,’ hasattr() will return true else, it will return false. The hasattr() function provides better readability compared to other conventional python methods used to check the attribute value. It is also helpful in checking keys to ignore unnecessary errors encountered while checking absent keys. With the help of examples, we will learn how to employ the hasattr() method of the Python language in this article. You’ll be able to effectively use the hasattr() function in your scripts by the end of this article. Let’s start with a basic illustration.

Example 1:

In the first example, we will define a simple class that contains the name of a student and the class in which the student studies. After that, we will check the attributes of the class with the hasattr() function. A user-defined class is created with the name ‘student,’ the first attribute is ‘Class’ and has value ‘5’, while the second attribute is ‘Name’ and has value ‘Tylor.’ The next step is to check the attributes of the class with the hasattr() function. First, we have checked the ‘Name’ attribute of the class, then the ‘Class’ attribute, and then the ‘FatherName’ attribute. Here you can view the code.

class Student:

  Class = 5

  Name = 'Tylor'

Student = Student()

print('The name of the student is:', hasattr(Student, 'Name'))

print('student\'s class  is:', hasattr(Student, 'Class'))

print('Student\'s father name is:', hasattr(Student, 'FatherName'))

The output of the above code is as follow:

If you observe that the first two outputs are ‘True.’ In contrast, the last output is ‘False.’ As discussed earlier, the hassttr() will return ‘True’, if a specified object has a certain specified object. In contrast, it returns ‘False’ if the certain object does not have a certain specified object. The class ‘Student’ has two attributes, ‘Class,’ ‘Name,’ while it does not have the ‘FatherName’ attribute, which is why the hasattr() function returns ‘False’ in this case.

Example 2:

Let us look at some complicated yet structured programs to get familiar with the functionality of the hasattr() function. Here, we defined a class using the def_init_() function. The class is again consisting of students’ data. It has two attributes, ‘RollNo’ and ‘grades.’ The data is provided to both attributes of the class by calling the class name; student (35, ’M’), where ‘35’ is the ‘RollNo’ and ‘M’ is the grade of the student. Later, we added another attribute in the class: the student’s age. This we can achieve by creating another instance of the class with another specified name; for example, student1 = student(), and student1.age = 9. Refer to the code given below to get a clear understanding of the program.

class student:
   def __init__(selff, rollNo, grades):
      selff.rollNo = rollNo
      selff.grades = grades
   def display (selff):
      print("The Roll number is : ", selff.rollNo)
      print("The Grade is :", selff.grades)
student1 = student(35, 'M')
student1.age=9
print(hasattr(student1, 'age'))

Text Description automatically generated

The output of the above code is as follow:

As you can see, the hasattr() function has returned ‘True’ since the ‘age’ attribute is added to the class in later steps.

Example 3:

Let us have a performance analysis of the hasattr() function compared to the try statement. In this example, we will see which one is better, the hasattr() function or the try statement of the python language. Let us see the code and output first, and then we will see which one is better than the other.

import time
class Comparison:
    name = "HasAttribute"
    time = 5
comp = Comparison()
startHasattr = time.time()
if(hasattr(comp, 'Time')):
    print("Time is there")
else:
    print("No Time")
print("The hasattr() has taken the time to execute : " + str(time.time() - startHasattr))
startTry = time.time()
try:
    print(comp.time)
    print("Time is there")
except AttributeError:
    print("No Time")
print("The try statement has taken the time to execute : " + str(time.time() - startTry))

Text Description automatically generated

As you can see, the class ‘Comparison’ has two attributes, ‘name’ and ‘time.’ First, we have implemented the hasattr() function to check whether the ‘Comparison’ class has the attribute ‘Time’ or not. Then we have checked the execution time of both hasattr() functions and try statement with the help of the time() function. The output of the above code is given below:

Text Description automatically generated

Note that hasattr() returned ‘False,’ yet the class ‘Comparison’ has the attribute ‘time.’ The key point to notice here is we have passed ‘Time’ in hasattr() while the ‘Comparison’ class has ‘time’ attribute. Python is a case-sensitive language, so ‘Time’ and ‘time’ are two different attributes. Moreover, if you see the execution time, you will notice that the try statement is faster than the hasattr() function. However, the hasattr() function provides better readability, which is why hasattr() is still preferred over the try statement.

Conclusion:

We learned about the Python hasattr() built-in function in this article. With the help of simple as well as complex examples, we have learned how to implement the hasattr() function in our programs. Furthermore, we have compared the execution time of hasattr() with the try statement, which proved that although try statement is fast, the hasattr() function is preferred due to its enhanced readability.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content