Using Python, the easiest way to check if object has an attribute is to use the Python hasattr() function.

if hasattr(obj, "upper"):
    print("Object has attribute upper!")
else:
    print("Object doesn't have attribute upper!")

We can also use exception handling to see if an object has an attribute in Python.

try:
    obj.upper()
    print("Object has attribute upper!")
except TypeError:
    print("Object doesn't have attribute upper!")

When working with objects in Python, it is useful to be able to easily check if an attribute exists in an object.

We can check if an object has an attribute with the Python hasattr() function. The hasattr() function will return if the object has the attribute or not.

Below are some examples of using the hasattr() function to check if different objects have various attributes.

print(hasattr("string","upper"))
print(hasattr(10,"upper"))
print(hasattr([1,2,3],"__iter__"))
print(hasattr({ "key1":"value1" },"lower"))

#Output:
True
False
True
False

Checking if an Object has an Attribute with Exception Handling in Python

Another way you can check if an object has an attribute is with exception handling in Python.

When we try to access an attribute in an object, and the attribute doesn’t exist, we will get an AttributeError. If we don’t get an AttributeError, we will know the object has the attribute.

Therefore, using this logic, we can check if an object has a particular attribute.

Below is an example in Python of checking if different objects have various attributes using exception handling.

try:
    0.lower()
    print('Object has attribute "lower"!')
except TypeError:
    print('Object doesn't have attribute "lower"!')

try:
    "power".lower()
    print('Object has attribute "lower"!')
except TypeError:
    print('Object doesn't have attribute "lower"!')

Object doesn't have attribute "lower"!
Object has attribute "lower"!

Hopefully this article has been useful for you to learn how to check if an object has an attribute or not in Python.

Categorized in:

Python,

Last Update: March 18, 2024