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.
- Python | range() method
- Python String Title method
- Python Number | uniform() method
- Python Number | fabs() method
- Python Strings encode() method
- Python Strings decode() method
- Python 3 Strings | expandtabs() method
- Python | getattr() method
- Python | next() method
- Python | setattr() method
- Python | iter() method
- Python | hash() method
- Python | object() method
- Python | bytes() method
- Python | set() method
- Python | isinstance() method
- Method Overriding in Python
- Extend Class Method in Python
- Instance method in Python
- How to clone a method code in Python?
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.