Knowing how to check an object's type in python before executing any operations on it is a fundamental task that you'll come across regularly whether you're working on a production system, or a personal project. If you're just getting started or have experience with the language, this will help to produce better code.
What is an Object?
To understand the concept well, one should remember that Python is primarily an object-oriented programming language. That means that everything in python is an object with properties and methods.
An object is an instance of a class. A class is a boilerplate or a blueprint of an object that contains all the methods and data variables necessary. For example, in Python, ‘int’ is a class. When we assign a number to a variable, the datatype ‘int’ is dynamically assigned to the variable.
How to Check the Type of an Object in Python?
There are many methods in python to determine the type of an object. The built-in type() function will be covered at first, followed by more complex techniques like the isinstance() function, the __class__ attribute, and others.
1) type() function
To determine the type of an object, this method the simplest way. The type() function is a built-in method in python that returns the type of an object as an argument. It will be useful to check the type for performing operations on it.
For instance, we can use the following code to determine the type of the integer 5:
x = 5 print(type(x))
As we can see, the output of the type() function is a class that represents the type of the object. In this case, the type of integer 5 is int.
The function returns the class name and it gives the complete necessary information about the object’s type. But, Python being the versatile language that it is, there are many other ways to find or check the Object type without explicitly using the ‘type()’ function.
2) isinstance() function
The isinstance() function takes an object and a class as arguments and returns True if the object is an instance of the class, and False otherwise. It compares both arguments and returned the boolean value of the comparison.
For example, to check if the integer 5 is an instance of the int class, we can use the following code:
x = 5 print(isinstance(x, int))
The isinstance() function returns a boolean value of True or False by comparing the class of the variable to the class passed as the argument in the function. In the above example, we’ve passed ‘x’ which has the integer 5 assigned to it as one argument and we’ve passed ‘int’ as the second argument.
However, it is only beneficial if one wants to check if the Object type is what they think it is because it does not return the type name. So, isinstance() function is more for the sake of verification than finding out.
03) . class__ attribute
As mentioned earlier in the article, everything in Python is an object and every object has its attributes the one attribute that would return the class type of the Object is aptly called the ‘__class__’ attribute. In addition to built-in functions, there is another way to check object type in Python is by using the __class__ attribute.
Python objects each have a __class__ attribute that includes the object's class information. For instance, the following code can be used to determine the class of integer 5.
x = 5 print(x.__class__)
The type() function essentially returns the __class__ attribute from the object. The above example is more of an explicit way of accessing the attribute without the need for any methods.
If we were to implement the functionality of isinstance() function without actually calling it, we can use the ‘==’ comparison operator to compare between the type we guess and the type of the object. Comparison operators return a boolean value of either True or False. ‘==’ returns True if two things being compared are equal and False if not equal.
4) The '==' operator and type()
Using the type() function and the == operator is another technique to determine an object's type. This can be used to contrast an object's type with a particular class. For instance, we can use the following code to determine whether the integer 5 is of type int:
x = 5 print(type(x) == int)
It's important to remember that Python is a dynamically typed language, which means that a variable's type may change while it is being used. Because of this, it may be required to confirm the type of an item before carrying out specific operations. To add two numbers, for instance, we must ensure that they are both integers or floats.
x = 15 print(type(x)) x = "text" print(type(x))
The above code demonstrates how the object type of a variable can change during runtime. The output for this example will be the following:
<class 'int'> <class 'str'>
The first print statement displayed the type to be ‘int’ as 15 is an integer but after a string was assigned to the same variable, the same print statement displayed the type to be ‘str’ because of the dynamic change of object type.
The dynamically typed nature of python makes the action of checking object types highly essential. For example, if we want to add two numbers, we need to make sure that both are integers or float. Operations on incompatible class types would result in errors that can only be debugged through functions like type() or through the other approach of accessing the ‘__class__’ attribute.
Also, learn how to get the class name in python.
In conclusion, knowing how to check an object's type in Python is essential for any beginner to comprehend the various techniques, their benefits and drawbacks, and when to apply them in various circumstances. While the type() function is preferred, you have other options in your stock.