Everything is an object in Python representing a specific type called βclassβ. The class exhibits the data of each object. Python contains a lot of data types. As a beginner, getting to know all these data types can be a little bit tricky at times. To clear this confusion, the type of the object can be checked by using various inbuilt Python functions like βtype()β and βisinstance()β. This article explains these functions in greater detail using practical examples.
How to Determine the Type of an Object in Python?
The type of an object in Python can be found in the following ways:
Letβs begin with the type() function.
Using type() Function
Python offers a built-in function named type() that retrieves the type of an object. Using the type() function will provide information about the βdata typeβ of the specified value. The function returns the βclass typeβ of the object. For example, using the type() function on an βintegerβ will get you the result β< class βintβ >β.
Syntax of type() Function With Single Parameter
Python type() function with a single parameter has the following syntax:
type(object)
The βtypeβ of the object will be returned if one argument is passed to the type() function.
Syntax of type() Function With Three Parameters
Python type() function with three parameters has the following syntax:
type(name, bases, dict)
In the case of three variables, a new type of object will be returned:
- βnameβ defines the name of the class.
- βbasesβ tell about the base classes.
- βdictβ describes the dictionary that aids in making the base class.
Example 1: Getting the Data Type of an Object
To demonstrate the working of the type() function, we will print the type of various data types:
print(type("I like to code in Python"))
print(type(13))
print(type(["Lauren", "Christina", "Amy"]))
print(type({
Β Β "Student": "Megan",
Β Β "Program": "Masters",
Β Β "Course": "Digital Arts",
Β Β "age": 24
}))
print(type(("Python", "Ruby", "TypeScript", "C#")))
print(type({"Guitar", "Piano", "Drums"}))
In this code:
- The βprint()β function is wrapped around the βtype()β function with different data types as their parameters.
- The code will print the data types of the given objects which in this case are βstringβ, βintegerβ, βlistβ, βdictionaryβ, βtupleβ, and βsetβ.
- The output will be given as β<class ‘data type’>β. The code prints out β<class ‘int’>β as 13 is an integer.
Output
The output of the above code is:
Example 2: Verifying the Type of Object With type()
The type of the object can be verified by comparing the return value of type() with a particular data type using βis datatypeβ. The data types can be int, str, list, dict, and more:
print(type(18) is int)
print(type(18) is str)
In this example:
- The number β18β is an βintegerβ and its data type needs to be validated.
- For that, the first line of code βprint(type(18) is int)β will print a Boolean value of βTrueβ since it’s an integer.
- While the second line of code print β(type(18) is str)β will print the Boolean expression βFalseβ since 18 is not a string.
Output
The output of the code is:
Using the isinstance() Function to Get the Objectβs Type
The Python function isinstance() returns βTrueβ if the βobjectβ in the argument belongs to the provided class/type or if it is a subclass inherited from the same class/type. The return value of the isinstance() function is the βBooleanβ which is True when the object belongs to a specified class or a derived class and False when it does not belong to either of those.
Syntax
The Python function isinstance() has the following syntax:
isinstance(obj, class)
While using isinstance(), the parameters given are:
- Object: The first parameter is the object that needs to be verified if it belongs to the class or not.
- Class: This refers to the class or type to which the object belongs.
Example: Getting Type of Object Using isinstance() Function
Let’s look at this code showing different scenarios to understand how the isinstance() function operates:
print(isinstance('Python', str))
print(isinstance(13, str))
print(isinstance("flowers", (str, int)))
- The βprint()β function is wrapped around the βisinstance()β function.
- In the first line, βprint(isinstance(‘Python’, str))β, the code checks if βPythonβ belongs to the βstring classβ using the βstrβ type parameter.
- In the second line, the number β13β is checked against the βstring classβ type.
- In the last line of code, the function contains the first parameter as βflowersβ and checks if it belongs to either the βstring or integer classβ by giving the parameters as βstrβ and βintβ.
Output
The output of the above code is:
- In the first scenario, it prints the output as βTrueβ since βPythonβ belongs to the βclass stringβ.
- The second case gives an output βFalseβ as β13 is not a stringβ.
- βflowersβ belong to the βstring classβ, hence, the final output is βTrueβ.
Real-Life Usage
- As Python is a βdynamically typed languageβ, hence knowing the type of parameters can save us a lot of stress. It helps in the βefficient running of the programβ as the data type is known prior to the programβs execution.
- This βremoves the chance of errorβ in the program.
- The Python function, type(), will βidentify the kind of data typeβ.
- Utilize the isinstance() function to ensure that the function only operates on certain object types.
Difference Between type() and isinstance()
The main difference between type() and isinstance() is how they handle the inheritance. isinstance() returns True for the instances belonging to the derived classes inheriting from the specified class whereas type() returns True only when the data type is exactly identical.
Letβs look at the following example that clearly explains the behavior of the type() and isinstance() functions:
class Parent:
Β Β pass
class Child(Parent):
Β Β pass
parent = Parent()
print(type(parent))
child=Child()
print(type(child))
print(type(child) is Child)
print(type(child) is Parent)
print(isinstance(child, Child))
print(isinstance(child, Parent))
In the above code,
- Two classes βParentβ and βChildβ are created where the βChildβ class gets an βinheritanceβ from the βParentβ class.
- An instance βparentβ of the βParentβ class is created. βprint(type(parent))β finds out the type of the object βparentβ. It prints out β<class ‘__main__.Parent’>β showing that βparentβ is an βinstanceβ of the βParentβ class.
- βchild = Child()β creates an instance βChildβ which is stored in the variable βchildβ.
- βprint(type(child))β will identify the type of the βchildβ object. β<class ‘__main__.Child’>β will be printed on the console which indicates that the βchildβ is an βinstanceβ of the βChildβ class.
- βprint(type(child) is Child)β will print βTrueβ representing that βchildβ is an βinstanceβ of the class βChildβ.
- βprint(type(child) is Parent)β will print βFalseβ as the type of βchildβ is βnot exactly identicalβ to the βParentβ class.
- βprint(isinstance(child, Child))β will print βTrueβ as the child is an βinstanceβ of the class βChildβ.
- βprint(isinstance(child, Parent))β will still print βTrueβ as although the βchildβ is an instance of the βChildβ class, it is also the βsubclassβ of the βParentβ class making βchildβ the βinstanceβ of the βParentβ class as well.
Output
The results of the code are demonstrated in the output below:
Thatβs all about finding the type of an object in Python as well as the functionality of the type() and isinstance() functions.
Conclusion
The type of an object in Python can be determined by various in-built functions like type() and isinstance() providing information about the objectβs data type. type() provides the specific data type of the object while isinstance() also verifies the inheritance determining whether an object belongs to a class or one of its derived classes. The type() function retrieves the data type of the variable.