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)
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()
Does name exist ? True Does motto exist ? False
Code #2 : Performance analysis
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.
- class method vs static method in Python
- Python | set() method
- Python | os.dup() method
- Python | next() method
- Python PIL | copy() method
- Python | os.WIFCONTINUED() method
- Python | isinstance() method
- Python | os.WIFSTOPPED() method
- Python | os.WIFSIGNALED() method
- Python | Decimal max() method
- Python PIL | blend() method
- Python | sys.getallocatedblocks() method
- Python | os.openpty() method
- Python | Decimal min() method
- Python | os.chdir() 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 firstname.lastname@example.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.