How to Determine the Type of an Object in Python?

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:

  1. Using the type() function
  2. Using the isinstance() function

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.