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
- Difference between Method Overloading and Method Overriding in Python
- Get() method for dictionaries in Python
- Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
- Python Program to detect the edges of an image using OpenCV | Sobel edge detection method
- Line detection in python with OpenCV | Houghline method
- Python | os._exit() method
- Python | os.WEXITSTATUS() method
- Python | os.abort() method
- Python | os.renames() method
- Python | os.lseek() method
- Python calendar module | formatmonth() method
- Python | PyTorch sin() method
- Python | Sympy Line.is_parallel() method
- Python PIL | GaussianBlur() method
- Python | range() method
- Python | Numpy np.hermefit() method
- Python | Numpy np.hermevander() method
- Python String Title method
- Python groupby method to remove all consecutive duplicates
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.