Various methods in Python to check type

In this short tutorial, we look at how to use Python to check type of objects. We take a look at all the various methods that can be used.

Table of Contents - Python Check Type:

  • Python check type
  • Using the type() function
  • Using isinstance()
  • Closing thoughts

TL;DR - How to check the type of an object in Python?

The type() function takes in an argument and returns the type of teh object. Apart from this method the isinstance() function can check if an argument is an instance of a particular class or type.

Python check type:

Unlike most programming languages Python does not require you to specify the data type of a particular object. Python assigns them during compilation. Experienced developers may not have a problem identifying data type, however, beginners might find this a little tricky.

Python facilitates this with the help of two in-built functions. We have explained both these methods in detail below.

Using the type() function:

The type() is used to check the type of an object. This function exists for this exact purpose and is the most commonly used method.

The type() method takes in an argument (object) and returns the class type assigned to the particular object.

The Syntax of type() is as follows:

type(object)

Code to check type using type()

language = "Python"
year =  1991
version = 3.9

print(type(language))
print(type(year))
print(type(version))
The output is as follows:
<class 'str'>
<class 'int'>
<class 'float'>

This is how we use type() to check the type of an object.

Using isinstance():

Isinstance can also be used to check type. However, unlike the type() function here we pass the classinfo along with the object the function returns a boolean value.

This will be true if the object belongs to a particular class and vice versa. However, do keep in mind that it only returns a boolean value in case it’s true and would not return the correct type in case it is false.

Syntax of isinstance():

isinstance(object, type)

Code using isinstance():

language = "Python"
year =  1991
version = 3.9

print(isinstance(language, str))
print(isinstance(year, int))
print(isinstance(version, int))
The output is as follows:
True
True
False

As the classinfo for version was passed as int, the isinstance method returns a false. This is how you use the isinstance() method.

Closing thoughts - Python check type

The type() method is the most recommended method to check the type of an object. The isinstance method stands out as it can be used to check if an object is part of a class as well.

Hence, I would always recommend using the type() method to check the type of an object.