Python | hasattr() method
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 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
Code #2 : Performance analysis
# Python code to demonstrate # performance analysis of hasattr() 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 other is not present.
Recommended Posts:
- class method vs static method in Python
- Python | next() method
- Python | set() method
- Python | os.dup() method
- Python | os.getenv() method
- Python | os.fsencode() method
- Python | os.getlogin() method
- Python | sympy.nC() method
- Python | os.sched_rr_get_interval() method
- Python | os.getppid() method
- Python | os.ctermid() method
- Python | os.strerror() method
- Python PIL | ImagePalette() Method
- Python | sympy.nP() method
- Python | sympy.apart() method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



