Check variable type in python

In this article, we will explore two different ways to check the type of a variable in python or more precisely, determine the type of data that a variable holds with example programs.

type() function
Python type() is a built-in function which accepts a value as argument and returns its data type. Example,

# a string
s = 'codippa'
print(type(s))

# an integer
num = 1
print(type(num))

# a float
d = 11.1
print(type(d))

# a list
nums = [1, 2, 3]
print(type(nums))

# a tuple
t = (1, 2, 3)
print(type(t))

# a dictionary
alpha = {'A': 1, 'B': 2}
print(type(alpha))

Actually, type() returns the class type of the value supplied and it is evident from the output of above code

<class ‘str’>
<class ‘int’>
<class ‘float’>
<class ‘list’>
<class ‘tuple’>
<class ‘dict’>

You can supply direct values to type. It is not necessary to supply a variable.
Thus, below syntax is also valid

print(type('codippa'))

isinstance() function
Python’s built-in isinstance() function checks if the type of a value matches some data type.
It accepts two arguments

  1. A value or variable.
  2. A class name

and checks if the data(or class) type of the supplied value or variable is the same as the given class type(second argument).

Python docs for isinstance() state,

Return whether an object is an instance of a class or of a subclass thereof.

isinstance() returns True if the type value matches with the class or its sub class and False otherwise. Example,

# a string
s = 'codippa'
print(isinstance(s,str))
# an integer
num = 1
print(isinstance(num, int))

# a float
d = 11.1
print(isinstance(d, int))

# a list
nums = [1, 2, 3]
print(isinstance(nums, list))

# a tuple
t = (1, 2, 3)
print(isinstance(t, tuple))

# a dictionary
alpha = {'A': 1, 'B': 2}
print(isinstance(alpha, dict))

This prints

True
True
False
True
True
True

Note that the second argument(or the class name) should not be enclosed in quotes.

isinstance() also takes sub-classes into account. That is, it will return True even if the type of value matches any of the subclass of the supplied class type.
Python documentation recommends the use of isinstance() over type() since it also checks for subclasses.

You can also provide a python tuple of class names as the second argument.
If the data type of value matches any of those classes or their subclasses, it will return True. Example,

s = 'codippa'
print(isinstance(s, (int, float, str)))

Above code will print True since class type of value is str.

Hope the article was useful.