Table of contents
1.
Introduction
2.
What is Python isinstance?
3.
Syntax of isinstance
3.1.
Examples of Python isinstance Function
4.
Python isinstance Function Handling Polymorphism
5.
How instance() Function works in Python?
5.1.
Python
6.
Advantages and Disadvantages of Python isinstance Function
7.
Frequently asked questions
7.1.
What does isinstance do in Python?
7.2.
What is the difference between the type () and isinstance () in Python?
7.3.
How to check isinstance list in Python?
8.
Conclusion
Last Updated: Sep 22, 2024
Easy

Python isinstance

Author Tashmit
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In Python, the `isinstance()` function is used to check if an object is an instance of a specified class or any of its subclasses. It takes two arguments: the object to be checked and the class or a tuple of classes. The function returns `True` if the object is an instance of the specified class(es) and `False` otherwise, providing a convenient way to perform type checking in Python programs. In this article we will discuss this in detail.

Python isinstance

In this article, we will study about isinstance function in Python. We will also study about the syntax, its examples, and its advantages and disadvantages in detail.

Also see,   reverse a string in python

What is Python isinstance?

The isinstance() function in Python is used to check if an object is an instance of a specified class or any of its subclasses. It takes the object and the class (or a tuple of classes) as arguments and returns True if the object is an instance of the specified class(es), and False otherwise. This function is commonly used for type checking and conditional branching based on object types.

Moving forward, let’s discuss the syntax of Python isinstance function.

Syntax of isinstance

The syntax of Python isinstance function is as below.

isinstance(object, classinfo)
You can also try this code with Online Python Compiler
Run Code


In the above syntax, the isinstance takes in two variables, object and classinfo. The classinfo is the class we want to check if the object is a part of that classinfo. It returns a boolean value. True if the object is an instance of the class, and False if its not. Let us have a look at some of the examples to understand better.

Examples of Python isinstance Function

The Python isinstance function can be used for various situations. For example,

To check if a variable belongs to a class. 

Code

x = 5
if isinstance(x, int):
   print("x is an integer")
else:
   print("x is not an integer")
You can also try this code with Online Python Compiler
Run Code


Output

Output

Explanation

In the above example, we checked whether x is belongs to an integer class or not. 

Python isinstance Function Handling Polymorphism

Python isinstance function can be useful to handle polymorphism as well. See below example for better understanding.

Code

class Ninja:
   def __init__(self):
       pass


class Python(Ninja):
   def __init__(self, Language):
       self.Language = "Python"


class Java(Ninja):
   def __init__(self, Language):
       self.Language = "Java"


language1 = Python(Python)
language2 = Java(Java)


print(isinstance(language1, Ninja))
print(isinstance(language2, Ninja))
print(isinstance(language1, Python))
print(isinstance(language2, Java))
You can also try this code with Online Python Compiler
Run Code


Output

Output

Explanation

In the above code, we used isinstance function to check polymorphism. We checked if the objects are present in the class are not. 

And  Convert String to List Python

How instance() Function works in Python?

The `isinstance()` function in Python works by checking if an object is an instance of a specified class or any of its subclasses. When you call `isinstance()` with an object and a class (or a tuple of classes) as arguments, it examines the inheritance hierarchy of the object to determine if it belongs to the specified class(es).

Let's see how the `isinstance()` function works internally:

1. The function first checks if the `classinfo` argument is a type or a class. If it is, it directly compares the type of the `object` argument with the `classinfo` using the `type()` function.

2. If the `classinfo` argument is a tuple, the function iterates over each class in the tuple and checks if the `object` is an instance of any of those classes.

3. For each class in the `classinfo` (either a single class or classes in a tuple), the function performs the following steps:

  • It checks if the class is a direct type of the `object` using the `type()` function. If there is a match, `isinstance()` returns `True`.
  • If the direct type check fails, the function examines the inheritance hierarchy of the `object`. It traverses through the object's class and its superclasses, comparing each class with the `classinfo` class.
  • If a match is found anywhere in the inheritance hierarchy, `isinstance()` returns `True`.

4. If the `object` is not an instance of any of the specified classes or their subclasses, `isinstance()` returns `False`.

The `isinstance()` function essentially checks the "is-a" relationship between the object and the specified class(es). It determines if the object is an instance of the class or any of its subclasses based on the inheritance hierarchy.

For example : 

  • Python

Python

class Animal:
pass

class Dog(Animal):
pass

class Cat(Animal):
pass

dog = Dog()
cat = Cat()

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

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

print(isinstance(dog, (Dog, Cat))) # Output: True
print(isinstance(cat, (Dog, Cat))) # Output: True
You can also try this code with Online Python Compiler
Run Code

In this example, `isinstance(dog, Dog)` returns `True` because `dog` is an instance of the `Dog` class. `isinstance(dog, Animal)` also returns `True` because `Dog` is a subclass of `Animal`, so `dog` is considered an instance of `Animal` as well.

On the other hand, `isinstance(dog, Cat)` returns `False` because `dog` is not an instance of the `Cat` class.

When a tuple of classes is provided, such as `isinstance(dog, (Dog, Cat))`, the function checks if `dog` is an instance of either `Dog` or `Cat`, and it returns `True` since `dog` is an instance of `Dog`.

Advantages and Disadvantages of Python isinstance Function

Below are the advantages and disadvantages of Python isinstance function.

Advantages 

  • Flexibility and Polymorphism: The code can handle objects of different classes which share a common interface. With this, we can reuse the code. Also, it simplifies the handling of diverse object types.
     
  • Inheritance Awareness: Python isinstance function considers objects to be an instance, This enhances the flexibility of object-oriented programming.
     
  • Dynamic Type Checking: Python isinstance function allows dynamic type checking. It adapts to changes in object types and provide flexibility in program structures.
     

Disadvantages

  • Complexity and Readability: The code readability is reduced when isinstance is used more often. It can become hard to read and understand the code.
     
  • Limited Type Information: It provides information about the type of the object, but it does not provide any information regarding object's attributes, 

    Also see, How to Check Python Version in CMD

Frequently asked questions

What does isinstance do in Python?

isinstance checks if an object is an instance of a specific class or a tuple of classes, returning True or False.

What is the difference between the type () and isinstance () in Python?

type() returns the exact type of an object, whereas isinstance() checks if an object is an instance of a class or its subclasses.

How to check isinstance list in Python?

To check if an object is a list in Python, use: isinstance(object, list). This returns True if object is a list.

Conclusion

In this article, we discussed the isinstance function in Python. We also studied about the syntax, its examples, and its advantages and disadvantages. To understand more about object-oriented programming, you can refer to below mentioned article

Object-Oriented Programming Python

You may refer to our Guided Path on Code Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Live masterclass