Write a Python Program to Differentiate Between type() and isinstance()

When working with Python, you might have come across two built-in functions, type() and isinstance().

These two functions are used to determine the type of a given object.

Although they seem similar, there are significant differences between them.

In this tutorial, we’ll take a closer look at these functions and differentiate between them.


type()

The type() function returns the class type of an object.

It takes a single argument, which is the object whose class type needs to be determined.

The returned value is a type object, which represents the class type of the given object.

Example:

a = 5
print(type(a)) # <class 'int'>

isinstance()

The isinstance() function checks if an object is an instance of a particular class or its subclasses.

It takes two arguments, the object whose type needs to be checked and the class or tuple of classes that need to be checked against.

The function returns a boolean value, True if the object is an instance of the class or tuple of classes, otherwise, False.

Example:

a = 5
print(isinstance(a, int)) # True

So, what’s the difference between type() and isinstance()?

The key difference between type() and isinstance() is that type() only checks the exact type of the object, while isinstance() checks if the object is an instance of a particular class or any of its subclasses.

In other words, type() returns a class object, while isinstance() returns a boolean value.

Here’s an example to understand the difference better:

class A:
    pass

class B(A):
    pass

b = B()
print(type(b)) # <class '__main__.B'>
print(isinstance(b, A)) # True

In the above example, type(b) returns <class '__main__.B'> because b is an instance of class B.

However, isinstance(b, A) returns True because b is also an instance of the superclass A.


In summary, both type() and isinstance() are useful for determining the type of an object in Python, but they have different use cases. type() checks for the exact type of the object, while isinstance() checks if the object is an instance of a particular class or any of its subclasses.