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
class GfG:
name = "GeeksforGeeks"
age = 24
obj = GfG()
print ( "Does name exist ? " + str ( hasattr (obj, 'name' )))
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
class GfG:
name = "GeeksforGeeks"
age = 24
obj = GfG()
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))
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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
05 Jul, 2022
Like Article
Save Article