Check if a Python Object Has Attributes

Check if a Python Object Has Attributes

  1. Check for Attributes Using the hasattr() Method in Python
  2. Check for Attributes Using the getattr() Function in Python

Object-oriented programming revolves around the concepts of classes and objects.

Each class has methods and properties that can be called attributes. An object can take the attributes of a class, and each object can also have its attribute. Knowing what attributes an object has, is necessary.

Checking attributes in an object manually in large pieces of code is not possible. This article will show the different ways to check the attributes of an object.

Check for Attributes Using the hasattr() Method in Python

The hasattr() function checks an object if it has a specific attribute or not. If the function finds the attribute, it returns true; else, it returns false.

Syntax:

hasattr(object_name, attribute_name)

There are two parameters to this function - the name of the object and the attribute, which we want to check. The function gives the output as Boolean true or false depending on whether it finds the attribute or not.

Say we have a class called Cake. We define three attributes inside this class - best_cake, best_flavor, and cost. Then, we create the cake_object as the object of this class.

Now, to check if this object has the attribute best_cake, we use the hasattr() method. Pass the name of the class and this attribute as an argument in this function.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(hasattr(Cake, 'best_cake'))

Output:

True

Since the best_cake attribute belongs to the object, cake_object, we get True as the output.

Now see what will happen if we pass quantity as the attribute name.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(hasattr(Cake, 'quantity'))

Output:

False

Since the attribute quantity does not exist, we get False as the output.

Use the hasattr() Function With If-Else Block in Python

One more way is to utilize the hasattr() function is to use it with the if-else block. The hasattr() function returns true when the attribute is present.

Thus, the if block executes and prints the attribute’s value. But if the attribute is absent, then the value returned will be false, and the else block executes.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
if hasattr(Cake, 'quantity'):
    print(Cake.quantity)
else:
    print("Whoops, no such attribute exists!")

Output:

Whoops, no such attribute exists!

We search for the attribute inside the if block. Since the attribute was not present, the function returned false and entered the else block. Inside the else block, we specify a simple print statement printed as the output.

Check for Attributes Using the getattr() Function in Python

The getattr() function returns a default value when an attribute is absent. The getattr() function works just like the previous one.

Syntax:

getattr(object_name, attribute_name, default_value)

The getattr() function takes three arguments - object, attribute, and a default value for cases when the attribute does not exist.

Say, we have to find the quantity attribute for the cake_object object. Without specifying a default argument, let’s use the getattr() function.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(getattr(Cake, 'quantity'))

Output:

AttributeError: type object 'Cake' has no attribute 'quantity'

The getattr() function throws an exception here.

Now, let us specify a default argument that should be printed when the attribute is absent. This default argument can be a simple message.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
print(getattr(Cake, 'quantity', 'Attribute not found'))

Output

Attribute not found

We get the message from the default argument instead of any exceptions or errors.

Use Getattr() Function With Try-Except Block

There is another way to use the getattr() function. Using the try-catch block to check the presence of an attribute. The idea is to include the getattr() function inside the try block.

If the attribute is present, we will print its value. Otherwise, the AttributeError will be thrown. We can handle this exception in the catch block and print an error message using the print statement.

We search for the quantity attribute inside the try block in this example. We do not specify the default argument inside the getattr() function.

It is because we handle the error inside the except block.

class Cake:
    best_cake = "Choco Lava"
    best_flavor = "Vanilla"
    cost = 2500
    
cake_object = Cake()
try:
    print(getattr(Cake, 'quantity'))
except AttributeError:
    print("Whoops, this attribute is not present!")

Output:

Whoops, this attribute is not present!

We cannot use the hasattr() function with try-catch block like the getattr() function. This is because the hasattr() function returns Boolean values and not the exceptions.

to Summarize

We discussed finding if an attribute is present in an object in Python. We used two functions - hasattr() and getattr() for achieving this.

We learned to combine the hasattr() function with the if-else block and the getattr() function with the try-except block.

Related Article - Python Object

  • Add Attribute to Object in Python
  • Fix Object Has No Attribute Error in Python
  • Fix Error List Object Not Callable in Python
  • Fix Object Is Not Subscriptable Error in Python
  • Python __repr__ Method