What are the differences between type() and isinstance()?

In Python, type() and isinstance() are both used to determine the type of an object, but they serve slightly different purposes:

    type():
        The type() function returns the type of an object.
        It returns a type object, which is the class that the object is an instance of.
        It's not recommended for checking if an object belongs to a specific class hierarchy, as it doesn't consider inheritance.
        It's generally used to get the type of an object, not to perform type checking.

    isinstance():
        The isinstance() function checks whether an object is an instance of a specific class or a tuple of classes.
        It takes inheritance into account, so it can determine if an object is an instance of a class or any of its subclasses.
        It's commonly used for more robust type checking, especially when dealing with class hierarchies and polymorphism.

Here's an example to illustrate the differences:

python

class Animal:
    pass

class Dog(Animal):
    pass

class Cat(Animal):
    pass

dog_instance = Dog()
cat_instance = Cat()

print(type(dog_instance))  # Output: <class '__main__.Dog'>
print(type(cat_instance))  # Output: <class '__main__.Cat'>

print(isinstance(dog_instance, Dog))     # Output: True
print(isinstance(dog_instance, Animal))  # Output: True
print(isinstance(cat_instance, Cat))     # Output: True
print(isinstance(cat_instance, Animal))  # Output: True
print(isinstance(dog_instance, Cat))     # Output: False
print(isinstance(cat_instance, Dog))     # Output: False

In this example, type() returns the specific class for each instance, while isinstance() checks whether the instances are instances of certain classes, including their subclasses.

For more robust and flexible type checking, especially when dealing with inheritance, isinstance() is generally the preferred choice over type().

Comments