How to Use hasattr Function in Python: Syntax and Examples
The
hasattr function in Python checks if an object has a specific attribute and returns True or False. Use it as hasattr(object, 'attribute_name') to safely test attribute existence before accessing it.Syntax
The hasattr function takes two arguments:
- object: The object you want to check.
- attribute_name: A string with the name of the attribute you want to check for.
It returns True if the attribute exists, otherwise False.
python
hasattr(object, 'attribute_name')
Example
This example shows how to use hasattr to check if an object has an attribute before accessing it to avoid errors.
python
class Car: def __init__(self, brand): self.brand = brand car = Car('Toyota') # Check if 'brand' attribute exists if hasattr(car, 'brand'): print(f"Car brand is: {car.brand}") else: print("Brand attribute not found.") # Check for a missing attribute if hasattr(car, 'color'): print(f"Car color is: {car.color}") else: print("Color attribute not found.")
Output
Car brand is: Toyota
Color attribute not found.
Common Pitfalls
Common mistakes when using hasattr include:
- Passing the attribute name without quotes (it must be a string).
- Assuming
hasattrchecks for methods only; it works for any attribute. - Using
hasattrto check for attributes that raise exceptions when accessed (it catches exceptions internally).
python
class Person: def __init__(self): self.name = 'Alice' @property def age(self): raise ValueError('Age not available') p = Person() # Wrong: attribute name without quotes causes error # hasattr(p, age) # NameError: name 'age' is not defined # Right: attribute name as string print(hasattr(p, 'name')) # True print(hasattr(p, 'age')) # False because property raises exception
Output
True
False
Quick Reference
Use this quick guide when working with hasattr:
- Purpose: Check if an object has an attribute.
- Arguments: object, attribute name as string.
- Returns:
TrueorFalse. - Use case: Avoid errors when accessing attributes that may not exist.
Key Takeaways
Use hasattr(object, 'attribute_name') to check if an attribute exists safely.
Always pass the attribute name as a string in hasattr.
hasattr returns True if the attribute exists, False otherwise.
It helps prevent errors when accessing missing attributes.
hasattr works for any attribute, including methods and properties.