Skip to content
Related Articles

Related Articles

Python hasattr() method

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 05 Jul, 2022
View Discussion
Improve Article
Save Article

Python hasattr() function is an inbuilt utility function, which is used to check if an object has the given named attribute and return true if present, else false. In this article, we will see how to check if an object has an attribute in Python.

Syntax of hasattr() function

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. 

Example 1:  Python hasattr() function example

Here we will check if an object has an attribute, to find attributes of the object in python we have demonstrated the following code.

Python3




# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
 
# initializing object
obj = GfG()
 
# using hasattr() to check name
print("Does name exist ? " + str(hasattr(obj, 'name')))
 
# using hasattr() to check motto
print("Does motto exist ? " + str(hasattr(obj, 'motto')))

Output: 

Does name exist ? True
Does motto exist ? False

Example 2: Performance analysis between hasattr() method and try statement

This is the Simple Ways to Check if an Object has Attribute in Python or not using performance analysis between hasattr() function and try statement.

Python3




import time
 
# declaring class
class GfG:
    name = "GeeksforGeeks"
    age = 24
 
# initializing object
obj = GfG()
 
# use of hasattr to check motto
start_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 motto
start_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 the other is not present.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!