Simple Ways to Check if an Object has Attribute in Python

Python is an object-oriented programming language, has the main emphasis on objects. Objects represent the real-world entities inside a class. A class acts as a blueprint for the object. It consists of data, i.e., variables and functions which act on that data. A class is a template consisting of the object’s variables and functions. Attributes contain information about an object. In this article, we shall be looking at how in python we can check if object has attribute.

What are attributes?

Attributes in a class are the variables that are shared among all the instances of a given class. With these attributes, we can describe characteristics for the class. Each instance in a class shall have the same value for each attribute.

Let us consider a class named ‘Sample.’ The class has an attribute named ‘var,’ which has a string value ‘Value1’. Then, we created two objects of the class – ‘obj1’ and ‘obj2’. Next, we shall print the attribute ‘var’ for both objects.

class Sample:
  var = 'Value1'

obj1 = Sample()
obj2 = Sample()

print(obj1.var)
print(obj2.var)

The output printed shall be the same for both the objects signifying that all the instances will have the same value for attributes.

Value1
Value1

Python Check If Object Has Attribute Using hasattr()

To check if an object in python has a given attribute, we can use the hasattr() function.

The syntax of the hasattr() function is:

hasattr( object, name )

The function accepts the object’s name as the first argument ‘object’ and the name of the attribute as the second argument ‘name.’ It returns a boolean value as the function output. It shall return ‘True’ if the attribute is present in the object and ‘False’ if the object does not contain that attribute.

Let us understand the use of the hasattr() function with an example. We shall first define a class named ‘Book’. The class Book consists of three attributes – ‘book_name’, ‘author_name’ and ‘publishing_year’. Here ‘book_name’ and ‘author_name’ store string values whereas ‘publishing_year’ stores integer value.

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

After creating the class, we shall create an object for the same class named ‘obj1’.

obj1 = Book()

Now, we shall use the hasattr() function. We will pass the object name ‘obj1’ as the first argument to the function and the attribute name ‘book_name’ as the second argument to the function. Then, we shall print the output of the hasattr() function.

print(hasattr(obj1,'book_name'))

The output will be ‘True’ because the attribute exists.

True

If we try to print an attribute name that does not exist, the function will output ‘False’.

print(hasattr(obj1,'no_of_pages'))

Output:

False

If we try to pass an object ‘obj2’ which does not exist, then the function value will be ‘False’ even if the attribute of the given name exists.

print(hasattr(obj2,'book_name'))

Output:

False

The Entire Code is:

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

obj1 = Book()

print(hasattr(obj1,'book_name'))
print(hasattr(obj1,'no_of_pages'))
print(hasattr(obj2,'book_name'))

Python Check If Object Has Attribute using getattr()

We can also use another method named getattr() to check if an object has an attribute or not. We can achieve this by including the function in a try-except block. That is how to hasattr() function also works in python. It implements the getattr() function, and if it throws an AttributeError, it shall execute the except block.

The syntax of the getattr() function is :

getattr(object, name[, default])

As the first argument, it accepts is the name of the object whose attributes have to be found. The second argument is the name of the attribute for the given object. Finally, it accepts a default argument which will be printed if the attribute does not exist. If the attribute exists in a given object, the getattr() shall return the value stored by the attribute. If it does not exist, it shall throw an attribute error.

Let us look at two ways of using the getattr() function to check if an object has an attribute.

Using the default argument

The getattr() function shall throw an AttributeError if the attribute does not exist. But if we specify a default argument as the third argument to the getattr() function, then that argument will be printed.

Let us take the same class ‘Book’ as taken in the above example. Now, we shall try to print an attribute which does not exist.

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

obj1 = Book()

print(getattr(obj1,'no_of _pages'))

Since the attribute is not present, it throws AttributeError.

AttributeError: 'Book' object has no attribute 'no_of _pages'

But, if we specify a default argument, then instead of throwing error, it will print that.

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

obj1 = Book()

print(getattr(obj1,'no_of _pages','Attribute does not exist'))

Output:

Attribute does not exist

Using the try catch block

We can also use a try-catch block to check if the attribute exists or not. We shall pass the getattr() function inside the try block. If the attribute exists, it will simply print the attribute’s value.

But, if it does not, then it shall throw an AttributeError. So then, we shall catch the AttributeError in the except block and print a statement saying that the attribute does not exist.

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

obj1 = Book()

try:
    print(getattr(obj1,'no_of_pages'))    
except AttributeError:
    print("Attribute does not exist")

Output:

Attribute does not exist

Python Check If Object Has Attribute using if else block

We can also use an if-else block for checking if the attribute exists or not. If the attribute exists, the hasattr() function shall return True, and the if block shall be executed, thereby printing the value of that attribute. But, if the attribute does not exist, then hasattr() shall return False, and the else part will be executed.

class Book:
  book_name = 'Digital Fortress'
  author_name = 'Dan Brown'
  publishing_year = 1998

obj1 = Book()

if hasattr(obj1, 'book_name'):
  print(obj1.book_name)
else:
  print('Attribute does not exist')

Since the attribute exists, it shall print the name of the book.

Digital Fortress

That is all for checking in python if an object exists or not. If you have any doubts in mind, do let us know in the comments below.

Until next time, Keep Learning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments