In python there are two ways to identify the type of object -
This of course also works for custom types:
class Test1 (object):
pass
class Test2 (Test1):
pass
a = Test1()
b = Test2()
type(a) is Test1 #True
type(b) is Test2 #True
Note that type() will only return the immediate type of the object, but won’t be able to tell you about type inheritance.
type(b) is Test1 #False
Using isinstance(obj, type) method - which returns whether the type of object is same as the type passed. This also tells you about type inheritance -
isinstance(b, Test1) #True
isinstance(b, Test2) #True
isinstance(a, Test1) #True
isinstance(a, Test2) #False
isinstance([], list) #True
isinstance({}, dict) #True
We generally prefer the isinstance() to ensure the type of an object because it will also accept derived types.
The second parameter of isinstance() also accepts a tuple of types, so it’s possible to check for multiple types at once. isinstance will then return true, if the object is of any of those types:
isinstance([], (tuple, list, set)) #True