Python isinstance Function with Examples

The isinstance function in Python serves the purpose of determining if a specified object is an instance of a particular class. If the object is indeed part of that class, the function will return True; if not, it will return False. Additionally, it will yield True if the class in question is a subclass of the specified class. The isinstance function requires two parameters: object and classinfo, and it produces a Boolean output of either True or False.

Python isinstance Function Syntax

The signature of the function is given below.

Example

isinstance(object, classinfo)

Parameters

  • object: It is an object of string, int, float, long or custom type.
  • classinfo: Class name.
  • Return

It returns boolean either True or False.

Python isinstance Function Examples with Different Data Types

Let us examine a few examples of the isinstance function to grasp its capabilities. The isinstance function is employed to determine if different variables are instances of their respective data types or classes.

1. Integer

Consider the following illustration to verify the integer type utilizing the isinstance function in Python.

Example

# Check if an integer is an int

n = 100

print(isinstance(n, int))

Output:

2. Float

Let's consider an example to verify the float data type utilizing the isinstance function in Python.

Example

# Check if a float is a float

pi = 3.14159

print(isinstance(pi, float))

Output:

3. String

For illustration, we will utilize the isinstance function in Python to verify the type of a string.

Example

# Check if a string is a string

name = "Johnny"

print(isinstance(name, str))

Output:

4. List

Let's consider an example to verify the List type utilizing the isinstance function in Python.

Example

# Check if a list is a list

colours = ["blue", "black", "brown"]

print(isinstance(colours, list))

Output:

5. Dictionary

Let’s consider an example to verify the Dictionary data type by utilizing the isinstance function in Python.

Example

# Check if a dictionary is a dict

person = {"name": "Ayan", "age": 30}

print(isinstance(person, dict))

Output:

6. Tuple

Let’s consider an example to verify the Tuple type utilizing the isinstance function in Python.

Example

# Check if a tuple is a tuple

point = (1, 5)

print(isinstance(point, tuple))

Output:

7. Set

Let’s consider an example to evaluate the Set data type by utilizing the isinstance function in Python.

Example

# Check if a set is a set

digits = {1, 2, 3, 4,5,6,7,8}

print(isinstance(digits, set))

Output:

8. Class

Let’s consider an example to verify the type of a class utilizing the isinstance function in Python.

Example

# Check if a custom class instance is an instance of that class

class Bike:

    pass

my_bike = Bike()

print(isinstance(my_bike, Bike))

Output:

Examples of Python isinstance Function with Classes and Inheritance

Let's explore additional examples of the isinstance function to gain a deeper understanding of its capabilities.

Python isinstance Function Example 1

In this instance, we are providing an object and a class to the function, which will return True solely if the object is an instance of the specified class. Refer to the example shown below.

Example

# Python isinstance() function example

class Student:

    id = 101

    name = "John"

    def __init__(self, id, name):

        self.id=id

        self.name=name

student = Student(1010,"John")

lst = [ 12,34,5,6,767 ]

# Calling function

print(isinstance(student, Student)) # isinstance of Student class

print(isinstance(lst, Student))

Output:

Output

True

False

Python isinstance Function Example 2

The function isinstance can be employed to verify whether an object belongs to a class that implements a particular interface. An interface can be described as a class that outlines a set of methods that other classes are required to implement.

Example

# Python isinstance() function example

class Animal:

    def speak(self):

        raise NotImplementedError

class Dog(Animal):

    def speak(self):

        return "Woof!"

class Cat(Animal):

    def speak(self):

        return "Meow!"

def make_animal_speak(animal):

    if isinstance(animal, Animal):

        return animal.speak()

    else:

        raise ValueError("Object is not an Animal")

my_dog = Dog()

my_cat = Cat()

print(make_animal_speak(my_dog))

print(make_animal_speak(my_cat))

Output:

Output

"Woof!"

"Meow!"

Python isinstance Function Example 3

This function additionally yields True when the object is an instance of a subclass, and the class serves as a parent class. Observe its operation in the example provided below.

Example

# Python isinstance() function example

# Declaring variables

class NumericList(list):

    def __init__(self):

        return None

num = NumericList()

# Calling function

print(isinstance(num, NumericList)) # True

print(isinstance(num, list)) # True

Output:

Output

True

True

Conclusion

To summarize, the isinstance function is a useful built-in feature in Python that allows us to verify if an object belongs to a specific class or one of its subclasses. This capability is particularly advantageous when handling code that involves multiple data types, or when developing libraries or APIs that must accommodate a wide range of input types. By employing isinstance, we can ensure that our code functions correctly across different input scenarios and enhances overall robustness.

Input Required

This code uses input(). Please provide values below: