+

Python | hasattr () method

hasattr () — it is a built-in utility function in Python that is used in many day-to-day software applications. 
His main task is — check if the object has the given named attribute and return true if present, false otherwise.

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: Demonstration of hasattr () work

# Python code for demonstration
# hasattr () works

  
# class declaration

class GfG:

  name = " Python.Engineering "

  age = 24

 
# object initialization

obj = GfG ()

 
# using hasattr () to check the name

print ( "Does name exist? " + str ( hasattr (obj, ` name` )))

 
# using hasattr () to check the motto

print ( "Does motto exist?" + str ( hasattr (obj, `motto` )))

Exit:

 Does name exist? True Does motto exist? False  

Code # 2 : Performance Analysis

< code class = "comments"> # Python code for demo
# hasattr () performance analysis

import time 

  
# class declaration

class GfG:

name = "Python.Engineering "

  age = 24

 
# object initialization

obj = GfG ()

 
# using hasattr to check if visa

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 try / in addition to check the 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))

Exit:

 No Motto Time to execute hasattr: 5.245208740234375e-06 No Motto Time to execute try: 2.6226043701171875e-06 

Result: normal try / throw takes less time than hasattr (), but for code readability, hasattr () is always the best choice.

Applications: this function can be used to validate keys to avoid unnecessary errors when accessing missing keys. The hasattr () chaining is sometimes used to avoid entering one related attribute when there is no other.

Get Solution for free from DataCamp guru