Python hasattr() Method: A Detailed Tutorial

Python Hasattr() Method

In object-oriented programming, attributes are an integral part of classes and objects, encapsulating critical properties and behaviors. Understanding and correctly using Python’s hasattr() function allows developers to verify the existence of these attributes efficiently and effectively. In this tutorial, we will dive deep into the mechanism of hasattr(), explore how it works in Python 2 and Python 3, and illustrate its use with detailed examples. Let’s get started

Python’s hasattr() method is a versatile function used to verify the existence of an attribute within a class. By returning a boolean value, it provides a simple yet efficient way to handle attribute checking in object-oriented programming. Its behavior varies between Python 2 and Python 3, where Python 2 will suppress exceptions and return False, while Python 3 raises an exception if the attribute is associated with exceptional circumstances.


Understanding the Need for Python hasattr() Function

In the world of Object-oriented programming, we deal with the representation or mapping of real-life scenarios to Classes and Objects. Objects can be seen as instances of a class, embodying specific attributes and behavior.

At times, we may come across situations wherein we need to check for the presence of an attribute occupied or contained by a Class. Python’s hasattr() method can efficiently accomplish this task. It helps in checking for the presence of an attribute in a Class.

Now that we have understood the necessity and origin of Python hasattr() method, let us understand the working of the same.


Delving into How Python’s hasattr() Function Works

A Python Class embodies its attributes and behavior through its instances (objects).

The hasattr() method is used to check for the presence of an attribute within a Class.

hasattr(Class, attribute)

The hasattr() method returns a boolean value, True if the attribute exists in the class, and False otherwise.

Example: Using hasattr() to Check for Existing Attribute

class Info:
  name = "JournalDev"
  lang = "Python"
  site = "Google"
print(hasattr(Info, 'lang'))

In the above example, the attribute ‘lang’ is contained by the class ‘Info’. Therefore, the hasattr() function returns True as the attribute ‘lang’ exists in the class.

Output:

True

Example: Using hasattr() to Check for Non-existent Attribute

class Info:
  name = "JournalDev"
  lang = "Python"
  site = "Google"
print(hasattr(Info, 'date'))

As demonstrated above, the hasattr() function returns False because the attribute ‘date’ is not present in the class.

Output:

False

Python 2 hasattr() vs Python 3 hasattr() Method

In Python 2, the hasattr() overpowers all the exceptions and returns False for a condition.

FeaturesPython 2 hasattr()Python 3 hasattr()
Check for attribute existenceYesYes
Return TypeBoolean (True/False)Boolean (True/False)
Exception HandlingSuppresses all exceptions and returns FalseRaises an exception if the attribute is associated with exceptional circumstances
Effect of exceptions on attribute existenceReturns False even if attribute exists but is associated with an exceptionException is raised, not able to determine attribute’s existence
Use CaseWhen you want to ignore exceptions and only check for attribute’s existenceWhen you want to consider exceptions while checking for attribute’s existence

For instance, if an attribute ‘A’ exists in a class but is involved with some exceptions. At this moment, the hasattr() will neglect all the exceptions and will return False even if the attribute ‘A’ happens to exist in the Class.

Contrarily, in Python 3, hasattr() raises an exception if the attribute is associated with exceptional circumstances.

Example: Using hasattr() in Python 2

class Info(object):
     @property
     def hey(self):
         raise SyntaxError
     def say(self):
         raise SyntaxError
obj = Info()

print(hasattr(obj,'hey'))
print(hasattr(obj,'say'))

In the code above, despite the syntax error caused by the decorator, the hasattr() method overlooks the exception, returning False, even if the attribute exists in the class.

Output:

False
True

Example: Using hasattr() in Python 3

In the following code, the hasattr() function raises an exception due to the Syntax Error associated with the attribute ‘hey’.

class Info(object):
     @property
     def hey(self):
         raise SyntaxError
     def say(self):
         raise SyntaxError
obj = Info()

print(hasattr(obj,'hey'))
print(hasattr(obj,'say'))

Output:

Traceback (most recent call last):

  File "c:\users\hp\appdata\local\programs\python\python36\lib\site-packages\IPython\core\interactiveshell.py", line 3319, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-20-e14f6e57b66e>", line 9, in <module>
    print(hasattr(obj,'hey'))

  File "<ipython-input-20-e14f6e57b66e>", line 4, in hey
    raise SyntaxError

  File "<string>", line unknown
SyntaxError

FAQs

What is Hasattr() in Python?

Hasattr() is a built-in Python function that checks whether an object or class has a specific attribute. It returns a boolean value – True if the attribute exists and False if it doesn’t.

How do you check if an object has an attr in Python?

You can use the hasattr() function in Python to check if an object has a particular attribute. For example, hasattr(object, 'attribute_name') will return True if ‘attribute_name’ exists in the object.

How do you see all attributes of an object in Python?

To see all the attributes of an object in Python, you can use the built-in dir() function. It returns a list of all the attributes and methods, including those inherited from its class(es), for the specified object.

How do you check the datatype of an object in Python?

To check the datatype of an object in Python, you can use the built-in type() function. This function returns the datatype of the object. For instance, type(object) will provide the datatype of the specified object.

What is Setattr() used for?

Setattr() is a built-in function in Python that is used to set a specific value to an object’s attribute. If the attribute doesn’t exist, setattr() creates it. The syntax is setattr(object, ‘attribute_name’, value).

Conclusion

In this comprehensive guide, we have delved into the nuances of Python’s hasattr() method across Python 2 and 3 versions. As we’ve seen, this versatile method can play a vital role in object-oriented programming. How else might you apply the hasattr() method in your Python projects?