Python : Difference between type() and isinstance()

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.

Example:

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'

Prints:

cannot check subclasses
definitely prints

 

Here’s why isinstance is better than type:

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.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.