Using Python, the easiest way to check if an attribute exists in an object is to use the Python hasattr() function.
if hasattr(obj, "lower"):
print("Object has attribute lower!")
else:
print("Object doesn't have attribute lower!")
We can also use exception handling to see if an attribute exists in an object in Python.
try:
obj.lower()
print("Object has attribute lower!")
except TypeError:
print("Object doesn't have attribute lower!")
When working with objects in Python, it is useful to be able to easily check if an object has a certain attribute or not.
We can check if an object has an attribute with the Python hasattr() function. The hasattr() function will return if the attribute exists or not.
Below are some examples of using the hasattr() function to check if different attributes exist.
print(hasattr("string","lower"))
print(hasattr(10,"lower"))
print(hasattr([1,2,3],"__iter__"))
print(hasattr({ "key1":"value1" },"upper"))
#Output:
True
False
True
False
Checking if an Attribute Exists with Exception Handling in Python
Another way you can check if an attribute exists with exception handling in Python.
When we try to access an attribute and the attribute doesn’t exist, we will get an AttributeError. If we don’t get an AttributeError, we will know the attribute exists.
Therefore, using this logic, we can check if an attribute exists in an object.
Below is an example in Python of checking if different attributes exist using exception handling.
try:
0.upper()
print('Object has attribute "upper"!')
except TypeError:
print('Object doesn't have attribute "upper"!')
try:
"power".upper()
print('Object has attribute "upper"!')
except TypeError:
print('Object doesn't have attribute "upper"!')
Object doesn't have attribute "upper"!
Object has attribute "upper"!
Hopefully this article has been useful for you to learn how to check if an object has an attribute or not in Python.