hasattr() is an inbuilt utility function in Python which is used in many day-to-day programming applications.
Its main task is to check if an object has the given named attribute and return true if present, else false.
Syntax : hasattr(obj, key)
Parameters :
obj : The object whose which attribute has to be checked.
key : Attribute which needs to be checked.
Returns : Returns True, if attribute is present else returns False.
Code #1 : Demonstrating working of hasattr()
# Python code to demonstrate# working of hasattr() # declaring class class GfG : name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # using hasattr() to check nameprint ("Does name exist ? " + str(hasattr(obj, 'name'))) # using hasattr() to check mottoprint ("Does motto exist ? " + str(hasattr(obj, 'motto'))) |
Output:
Does name exist ? True Does motto exist ? False
Code #2 : Performance analysis
# Python code to demonstrate# performance analysis of hasattr()import time # declaring class class GfG : name = "GeeksforGeeks" age = 24 # initializing objectobj = GfG() # use of hasattr to check mottostart_hasattr = time.time()if(hasattr(obj, 'motto')) : print ("Motto is there")else : print ("No Motto") print ("Time to execute hasattr : " + str(time.time() - start_hasattr)) # use of try/except to check mottostart_try = time.time()try : print (obj.motto) print ("Motto is there")except AttributeError : print ("No Motto")print ("Time to execute try : " + str(time.time() - start_try)) |
Output:
No Motto Time to execute hasattr : 5.245208740234375e-06 No Motto Time to execute try : 2.6226043701171875e-06
Result : Conventional try/except takes lesser time than hasattr(), but for readability of code, hasattr() is always a better choice.
Applications : This function can be used to check keys to avoid unnecessary errors in case of accessing absent keys. Chaining of hasattr() is used sometimes to avoid entry of one associated attribute if other is not present.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


