How to Check the Type of Variables in Python?

How to Check the Type of Variables in Python?

Answer: You can use the built-in type() method to determine Python variables.

We generally get to know about the type of variable just by the value it got assigned, whereas in some cases we want to check about the type of variable. This can be done by using the Python built-in functions and modules which are discussed below:

Table of Contents:

Methods to Determine Data Type of Python Variables

The following are some of the most common methods that are used to determine the variable type in Python:

Method 1: Using type() Function to Determine Variables in Python

When you are working with a variable and you want to know about the type of data you are dealing with, the type() function can provide you with the type of data. It is also used in the debugging process because, in Python, variables are not declared with the data type they belong to.

Example:

Python

Output:

Using type() Function to Determine Variables in Python-output

Method 2: Using isinstance() Function to Determine Variable Type in Python

It is a built-in function with more flexible operations. This function contains two arguments. If the first argument is an instance of the class of the second argument, accordingly the boolean value gets printed.

Example:

Python

Output: 

Using isinstance() Function to Determine Variable Type in Python

Method 3: Using typing module in Python

It is the advanced method of determining the data type. You can use a typing module when you are assigned with large codebase and you need to know about its type.

Example:

Python

Output:

 Using typing module in Python-output

Method 4: Using __class__ attribute to Determine Variable Type in Python

Unlike type() function, __class__attribute is special as it doesn’t require a function call. This attribute can directly give the variable class.

Example:

Python

Output:

Using __class__ attribute to Determine Variable Type in Python-output

Method 5: Using type Hinting with the Variables in Python

It gives a hint about the type of data and the function returns the value. This method helps the developer to understand easily.

Example:

Python

Output:

Using type Hinting with the Variables in Python-output

Conclusion

Knowing the datatype is more important when dealing with a larger codebase. The type of data can be identified by the methods discussed above. And these are flexible approaches to get to know about the datatypes.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner