Today we’ll see how to check the object type in Python. We’ll be making use of two functions: type and isinstance.
Check the Object Type Using the type Function
So, the first function, type, returns the type of the object passed as an argument to it. It may be a variable or a literal expression.
Below you can see examples of objects of various data types, like strings, integers, floating point numbers or booleans. There are also collections like lists or tuples. And also functions and classes. As far as the latter are concerned, they are of type TYPE. In general, the names of the types are sometimes slightly different from the names we normally use, so for example the name of the string type is STR, as you can see in the first example below. One more thing to notice: you can pass whole expressions to the type function and then you will be informed about the type of the result of evaluating the expression. You can find some examples illustrating this in the code below as well. And here are the examples:
# string
>>> type('one')
<class 'str'>
# float
>>> type(4.5)
<class 'float'>
# integer
>>> type(-2)
<class 'int'>
# boolean
>>> type(False)
<class 'bool'>
# list
>>> type([1, 2, 3])
<class 'list'>
# tuple
>>> type(()) # empty tuple
<class 'tuple'>
# boolean expression
>>> type(2 < 8)
<class 'bool'>
# function expression
>>> type(len("hi"))
<class 'int'>
# conditional expression
>>> a = "one" if 3 != 2 + 1 else 1
>>> type(a)
<class 'int'>
# function
>>> def n():
... print(1)
...
>>> type(n)
<class 'function'>
# class
>>> class A:
... pass
...
>>> type(A)
<class 'type'>
>>>
The isinstance Function
The isinstance function, on the other hand, returns a boolean value. You can use it to confirm an object’s type. It takes two arguments. The first argument is the object whose type you want to confirm and the second argument is the type itself. The name of the type is used just like with the type function, so, for example, if you want to confirm that an object is a string you pass STR as the name of the type, as you can see in the second example below.
>>> isinstance(3, int)
True
>>> isinstance('yes', str)
True
>>> isinstance(3 + 2 == 5, bool)
True
Interestingly, bools are also treated as ints, where False is equal to 0 and True is equal to 1. Although it looks strange, but if we use True and False in calculations, it works:
>>> 2 * True - False # same as 2 * 1 - 0
2
Thus we have:
>>> isinstance(3 + 2 == 5, int)
True
>>> isinstance(True, int)
True
And some more examples:
>>> a = [3, 6, 7]
>>> isinstance(a, list)
True
>>> isinstance(10 / 2, int) # true division returns a float
False
>>> isinstance(10 / 2, float)
True
Using the two functions, type and isinstance, it’s very easy to check the object type in Python.
And here’s the video version of the post: