type() vs isinstance() in Python
By Lenin Mishra
Importance of type checking in Python
Python is a dynamically typed language. A variable can be assigned multiple values during the code lifetime.
x = "Pylenin" #string
x = 1992 #integer
x = [1, 2, 3] #list
So it is necessary to keep track of the data type that your variable is holding at a certain stage of the code.
That’s where built-in functions like type()
and isinstance()
come into play.
Example 1 - Checking data type of a variable
Code
x = "Pylenin"
# Check type of x
print(type(x))
# Perform boolean comparison
# Using is operator
print(type(x) is str)
Output
<class 'str'>
True
True
The isinstance()
function allows you to perform the above boolean comparison.
Code
x = "Pylenin"
# Using isinstance
print(isinstance(x, str))
Output
True
Difference between isinstance
and type
Difference 1 - Speed
The isinstance()
function is faster than the type
function. We can compare both their performance by using the timeit library.
>>> python -m timeit -s "x = 'Pylenin'" "type(x) is str"
5000000 loops, best of 5: 60.4 nsec per loop
>>> python -m timeit -s "x = 'Pylenin'" "isinstance(x, str)"
5000000 loops, best of 5: 42.7 nsec per loop
As you can see, the isinstance()
function is 30 times faster than type()
function.
Difference 2 - isinstance
can check for subclass, type
cannot
The isinstance()
method can check if an object belongs to either a class or a subclass. type
cannot check this.
Code
class Person:
def __init__(self):
self.type = "human"
class Pylenin(Person):
name = "Pylenin"
myself = Pylenin()
print(type(myself) is Pylenin)
print(isinstance(myself, Pylenin))
Output
True
True
Since myself
is an object of Pylenin
class, both type()
and isinstance()
return True.
However, Pylenin
inherits from Person
class. It’s the subclass of Person
class.
So ideally, myself
should also belong to Person
class.
Code
class Person:
def __init__(self):
self.type = "human"
class Pylenin(Person):
name = "Pylenin"
myself = Pylenin()
print(type(myself) is Person)
print(isinstance(myself, Person))
Output
False # type() returned False
True
As you can see, the type()
function is unable to link myself
object to the Person
class.
So type()
doesn’t work with inheritance.
Why should you choose isinstance
over type
?
There are 2 reasons to choose isinstance()
function over type()
.
isinstance()
is faster thantype()
.isinstance()
can deal with inheritance andtype()
cannot.
Learn more about the applications of isinstance() function in Python.