Python Type Isinstance

Instance and Type both are used to check the type of object. Instance can check the type of subclass too where as type can't.

In [4]:
!python --version
Python 3.6.10 :: Anaconda, Inc.

type in Python

Check if type is Integer

In [1]:
x = 1
In [6]:
print(type(x))
<class 'int'>

Check if type is Float

In [8]:
x = 1.5
In [9]:
print(type(x))
<class 'float'>

Check if type is String

In [10]:
x = 'john'
In [11]:
print(type(x))
<class 'str'>
In [12]:
x = 'j'
In [13]:
print(type(x))
<class 'str'>

Check if type is Class

In [14]:
class demo():
    pass
In [22]:
print(type(demo()))
<class '__main__.demo'>
In [23]:
type(demo())==demo
Out[23]:
True

isinstance in Python

isinstance can be used to check the type of object.

In [24]:
x = 1
In [25]:
isinstance(x,int)
Out[25]:
True
In [26]:
isinstance(x,float)
Out[26]:
False
In [27]:
x = 1.2
In [28]:
isinstance(x,float)
Out[28]:
True

isinstance can check the type of subclass too.

In [29]:
class computer():
    pass
class laptop(computer):
    pass
In [31]:
isinstance(computer(),computer)
Out[31]:
True
In [32]:
isinstance(laptop(),computer)
Out[32]:
True

Note, type can not check the type of subclass.

In [33]:
type(laptop())==computer
Out[33]:
False