The hasattr()
function checks if an object has a specific attribute. It returns True
if the attribute exists, otherwise False
. This is useful for avoiding errors, checking object properties dynamically, and handling flexible data structures.
Example
class Person:
def __init__(self, name):
self.name = name
p = Person("Alice")
print(hasattr(p, "name"))
# Output: True
print(hasattr(p, "age"))
# Output: False
This prevents errors from accessing missing attributes.
Syntax
hasattr(object, attribute_name)
- object → The object to check.
- attribute_name → The name of the attribute (as a string).
- Returns →
True
if the attribute exists, otherwiseFalse
.
1. Using hasattr()
Before Accessing an Attribute
Avoid AttributeError
when working with unknown objects.
if hasattr(p, "name"):
print(p.name)
else:
print("Attribute not found.")
Useful when working with dynamic data.
2. Checking Methods in a Class
You can also check if an object has a specific method.
class Car:
def drive(self):
return "Driving"
car = Car()
print(hasattr(car, "drive"))
# Output: True
print(hasattr(car, "brake"))
# Output: False
Great for handling objects flexibly in larger applications.
3. Using hasattr()
with Dictionaries
When working with objects that act like dictionaries, hasattr()
can be useful.
class Config:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
settings = Config(debug=True, theme="dark")
print(hasattr(settings, "debug"))
# Output: True
print(hasattr(settings, "mode"))
# Output: False
Perfect for storing dynamic settings or configurations.
4. Using hasattr()
to Validate User Input
Before accessing user-provided attributes, check if they exist.
user_input = "age"
if hasattr(p, user_input):
print(getattr(p, user_input))
else:
print("Invalid attribute.")
Avoids crashes from invalid input.
Key Notes
- ✔ Checks if an object has a specific attribute.
- ✔ Prevents
AttributeError
by validating before access. - ✔ Works with both instance variables and methods.
- ✔ Useful for dynamic configurations, user input, and debugging.
By using hasattr()
, you can handle objects more safely and dynamically, making your code robust and flexible. 🚀