Python Notes

The difference between type() and isinstance()

Although the type() function returns the type of the argument passed, it can be used to check whether the argument belongs to a certain type:

>>> a = 10
>>> b = [1,2,3]
>>> type(a) == int
True
>>> type(b) == list
True
>>> type(a) == float
False

Unlike type(), the isinstance() function is specially created to check if the data belongs to a specific class (data type):

>>> isinstance(a,int)
True
>>> isinstance(b,list)
True
>>> isinstance(b,tuple)
False
>>> c = (4,5,6)
>>> isinstance(c,tuple)
True

In addition, isinstance() allows you to check for belonging to at least one of the types listed in the tuple:

>>> isinstance(a,(float, int, str))
True
>>> isinstance(a,(list, tuple, dict))
False

Another difference isinstance(). This function supports inheritance. For isinstance(), the instance of the derived class is also an instance of the base class. For type(), this is not the case:

>>> class A (list):
...     pass
... 
>>> a = A()
>>> type(a) == list
False
>>> type(a) == A
True
>>> isinstance(a,A)
True
>>> isinstance(a,list)
True