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 | next() method
- Python | Tensorflow tan() method
- Python | os.strerror() method
- Python | Tensorflow abs() method
- Python | Method Overloading
- Python | bytes() method
- Python | os.chflags() method
- Python | range() method
- Python | object() method
- Python | os.uname() method
- Python | getattr() method
- Python | Tensorflow exp() method
- Python | iter() 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.