In short type checks the object passed to it is object of the exact class or subclass it is passed, however isinstance checks if object passed come under inheritance hierarchy of base class. Hence it is preferred to check isinstance over type.
type() simply returns the type of an object.
Whereas, isinstance(): returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
class MyString(str): pass my_str = MyString() if type(my_str) == 'str': print 'I hope this prints' else: print 'cannot check subclasses' if isinstance(my_str, str): print 'definitely prints'
cannot check subclasses definitely prints
isinstance is better than
class Vehicle: pass class Truck(Vehicle): pass
in this case, a truck object is a Vehicle, but you’ll get this:
isinstance(Vehicle(), Vehicle) # returns True type(Vehicle()) == Vehicle # returns True isinstance(Truck(), Vehicle) # returns True type(Truck()) == Vehicle # returns False, and this probably won't be what you want.
In other words,
isinstance is true for subclasses, too.