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 | next() method
- Python | set() method
- Python | PyTorch tan() method
- Python | setattr() method
- Python | object() method
- Python | hash() method
- Python | Tensorflow cos() method
- Python | range() method
- Python | iter() method
- Python | PyTorch cos() method
- Python | os.chflags() method
- Python | Tensorflow exp() method
- Python | Tensorflow abs() method
- Python | os.chmod method