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
isinstance() come into play.
Example 1 - Checking data type of a variable
x = "Pylenin" # Check type of x print(type(x)) # Perform boolean comparison # Using is operator print(type(x) is str)
<class 'str'> True True
isinstance() function allows you to perform the above boolean comparison.
x = "Pylenin" # Using isinstance print(isinstance(x, str))
Difference 1 - Speed
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
Difference 2 -
isinstance can check for subclass,
isinstance() method can check if an object belongs to either a class or a subclass.
type cannot check this.
class Person: def __init__(self): self.type = "human" class Pylenin(Person): name = "Pylenin" myself = Pylenin() print(type(myself) is Pylenin) print(isinstance(myself, Pylenin))
myself is an object of
Pylenin class, both
isinstance() return True.
Pylenin inherits from
Person class. It’s the subclass of
myself should also belong to
class Person: def __init__(self): self.type = "human" class Pylenin(Person): name = "Pylenin" myself = Pylenin() print(type(myself) is Person) print(isinstance(myself, Person))
False # type() returned False True
As you can see, the
type() function is unable to link
myself object to the
type() doesn’t work with inheritance.
Why should you choose
There are 2 reasons to choose
isinstance() function over
isinstance()is faster than
isinstance()can deal with inheritance and
Learn more about the applications of isinstance() function in Python.