Python isinstance() function with Examples

By | December 19, 2021

With the type() function, we can check the data type or class type of a data object. But with the isinstance() function we can check if a data object is an instance of a specific data type or class.

For example, if we define a variable x=20, with the help of isinstance() function we can check if the x variable is an int or float.

In this Python tutorial, we are going to break the isinstance() function and learn how to use it in Python. By the end of this tutorial, you should be able to tell

  • What is the isinstance in Python?
  • How to use the isinstance() function in Python?
  • How to check different data types with the isinstance function.

So let’s get started.

What is isinstance in Python?

The isinstance() is an inbuilt function that checks whether the specified value is an instance or object of the specified class or data type.

Vamware

Isinstance Syntax

The following is the syntax of isinstance() function

isinstance(object, classinfo)

Arguments

Vamware

The isinstance() function accept two arguments, and both the arguments are necessary.

  1. object : It can be a variable name or data value which data type we want to check.
  2. classinfo : The classinfo can be a single, tuple, or union of data types or class names.

Note: The class info can be a union of data types, and this update introduced in Python 310

Return

The isinstance() check if the specified object is an instance of classinfo, it returns True, otherwise, it returns False.

If the classinfo attribute is not a valid data type or class name the function returns a TyprError.

How to use the isinstance() function in Python?

The isinstance() function can check or test if a given variable is an object or instance of a specified type. For the inheritance using the isinstance() function, we can test if the specified class is the parent class of an object.

Here are the steps to use isinstance in Python

Step 1: Pass the first argument to the isinstance() function

The first argument of the isinstance method must be a valid variable name or the data value.

Step 2: Pass the second argument value to the function.

In the second argument, we can pass a single, tuple, or a union of data types or class names.

Example

isinstance(1, int)  #single classinfo argument
isinstance(1, (int, float, str))    #tuple classinfo argument
isinstance(1, int | float | str)    #union classinfo arguments

Step 3: Store the return value

The isinstance() function returns a boolean value, it could either be True or False. We can store the return value in a new variable or directly use the isinstance() statement with the conditional statement.

Python isinstance function example

Let’s check if the given number is an instance of int or not. We can also say let’s check if the given number is an int or not.

#given number
num = 90

#check if the number is an integer or not
is_int = isinstance(num, int)

print(f"Is {num} is an int?", is_int)

Output

Is 90 is an int? True

Python isinstance function with Built-In Data Types

In Python, every variable that holds a value has a data type. To check the data type we can use the type() function, and to verify if the variable has a type of specific data type we can use the isinstance() function.

Using the isinstance function we can check if the given variable is an int, float, list, tuple, str, set, dictionary, etc.

isinstance Examples

Check if the given variable is a float using the Python isinstance function

To check if the variable is an instance of float data type we can use the isinstance function with the float classinfo attribute.

#given numbers
num1 = 40
num2 = 40.0

#check if the number is an float or not
is_float_1 = isinstance(num1, float)
is_float_2 = isinstance(num2, float)

print(f"Is {num1} an float?", is_float_1)
print(f"Is {num2} an float?", is_float_2)

Output

Is 40 an float? False
Is 40.0 an float? True

Check if the given variable is a list, tuple, set or dictionary using the Python isinstance function

For the list, tuple, set, and dictionary, the data type keywords are, list, tuple, set, and dict respectively.

#list
my_list = [1,2,3,4,5,6]
print(f"Is {my_list} a list?", isinstance(my_list, list))

#tuple
my_tuple = (1,2,3,4,5,6)
print(f"Is {my_tuple} a tuple?", isinstance(my_tuple, tuple))

#set
my_set = {1,2,3,4,5,6
print(f"Is {my_set} a set?", isinstance(my_set, set))

#dictionry
my_dict = {'a':1, 'b':2, 'c':3}
print(f"Is {my_dict} a dict?", isinstance(my_dict, dict))

Output

Is [1, 2, 3, 4, 5, 6] a list? True
Is (1, 2, 3, 4, 5, 6) a tuple? True
Is {1, 2, 3, 4, 5, 6} a set? True
Is {'a': 1, 'b': 2, 'c': 3} a dict? True

Check if the given variable is a string using the Python isinstance function

To check if a variable is a string, we can use the str keyword as a classinfo attribute for the isinstance() function.

#given variables
var1 = "20"
var2 = 20

#results
is_str_1 = isinstance(var1, str)
is_str_2 = isinstance(var2, str)

print(f"is {var1} a string?", is_str_1)
print(f"is {var2} a string?", is_str_2)

Output

is 20 a string? True
is 20 a string? False

Note: Even for the empty string, it will have a string data type

#given string
empty_string = ''

print("is empty_string a string?", isinstance(empty_string, str))

Output

is empty_string a string? True

Python isinstance() function with multiple classinfo names.

The classinfo attribute of the isinstance(object, classinfo) function can also be a tuple or a set of unions.

Suppose you have two variables a and b, and you want to check if the variables are numbers on which Python supports the arithmetic operations. In such a case the numbers could be any of three data types int, float, or complex.

Here instead of checking the variable instance on individual data types, we can specify a tuple of data type as an attribute to the classinfo, and the isinstance() function will return True if the variable belongs to any of the thee data types.

Example

def add(a, b):
    # check if a is valid numbers
    if isinstance(a, (int, float, complex)):
        print("a is a valid number")
    else:
        print("a is not a valid number")
        return

    # check if b is valid numbers
    if isinstance(b, (int, float, complex)):
        print("b is also a number")
    else:
        print("b is not a valid number")
        return

    print("a + b=",a+b)

#int, int
add(1, 2)

print()

#float, int
add(2.3, 4)

print()

#complex, float
add(3.3+3j, 3.3)

print()

#str, float
add("34", 34.3)

Output

a is a valid number
b is also a number
a + b= 3

a is a valid number
b is also a number
a + b= 6.3

a is a valid number
b is also a number
a + b= (6.6+3j)

a is not a valid number

In Python 3.10 we can also use the union | (pipe) operator for multiple classinfo names, instead of tuples.

Example

def add(a, b):
    # check if a is valid numbers
    if isinstance(a, int | float | complex):
        print("a is a valid number")

    else:
        print("a is not a valid number")
        return

    # check if b is valid numbers
    if isinstance(b, int | float | complex):
        print("b is also a number")

    else:
        print("b is not a valid number")
        return

    print("a + b=",a+b)

#int, int
add(1, 2)
print()

#float, int
add(2.3, 4)
print()

#complex, float
add(3.3+3j, 3.3)

print()

#str, float
add("34", 34.3)

Output

a is a valid number
b is also a number
a + b= 3

a is a valid number
b is also a number
a + b= 6.3

a is a valid number
b is also a number
a + b= (6.6+3j)

a is not a valid number

Python isinstance() With Custom Classes

By far we discussed how can we check if a variable is an instance of a built-in data type. Now let’s test if a given object is an instance of a custom class.

In Python, we can create a custom class using class keywords, and a class can have multiple objects. With the isinstance() function we can check among the multiple classes and multiple objects which object belongs to a specific class.

Syntax

In case of instance check for custom class we follow the following syntax

isinstance(object_name, class_name)

Example

class Student():
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

class Teachers():
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

#create an object of Student
stu1 = Student("Rahul", 17, 12)

print("Is stu1 an object of Teachers Class?", isinstance(stu1, Teachers))

print("Is stu1 an object of Student Class?", isinstance(stu1, Student))

Output

Is stu1 an object of Teachers Class? False
Is stu1 an object of Student Class? True

Python isinstance() With Inheritance

In Python Inheritance a class can inherit from one or multiple parent classes. In inheritance, the object of subclass belongs to both the child class and the parent class.

For example, if the Teacher class is the Child class of the Staff class then the object of Teacher class also be an object of Staff class, such as isinstance(teacher1, Staff).

The isinstance() function works on the is-a relationship concept and in the case of inheritance, the object of the derived class also becomes the object of the Parent class.

Example

class Staff():
    def __init__(self, role, department):
        self.role = role
        self.department = department

    def show(self):
        print(self.role, self.department)

class Teachers(Staff):
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

        # call the super parent class
        super().__init__("teacher", "computer science")

techer1 = Teachers("Neha", 25000)

print("Is the teacher1 object an instance of Staff Class")
print(isinstance(techer1, Staff))

print("\nIs the teacher1 object an instance of Teacher Class")
print(isinstance(techer1, Staff))

Output

Is the teacher1 object an instance of Staff Class
True

Is the teacher1 object an instance of Teacher Class
True

In this example, you can see that the object teacher1 is the object of Teacher() class. Just because it inherits the Staff class, teacher1 also becomes the instance of Staff class.

Common Example Scenario of isinstance() function

Let’s say you have a list of multiple numbers of different data types. And you need to filter that list by putting all those items into different lists based on their data type.

For example, the string numbers must go to the str_list, the integer number must be in the int_list, and so on.

Solution

# given list
numbers = [1, 2.3, 14, 25.7, 88, 3+4j, '34', '6', 6+3j, '3.4', 26, 38.39]

# list that will store integers
int_list = []

# list that will store float
float_list = []

# list that will store string
str_list = []

# list that will store complex
complex_list = []

for number in numbers:
    # if the number is an integer
    if isinstance(number, int):
        int_list.append(number)

    # if the number is a float
    elif isinstance(number, float):
        float_list.append(number)

    # if the number is a string
    elif isinstance(number, str):
        str_list.append(number)

    # if the number is a complex number
    elif isinstance(number, complex):
        complex_list.append(number)

print("Int list", int_list)
print("Float list", float_list)
print("Str list", str_list)
print("Complex list", complex_list)

Output

Int list [1, 14, 88, 26]
Float list [2.3, 25.7, 38.39]
Str list ['34', '6', '3.4']
Complex list [(3+4j), (6+3j)]

Conclusion

Now let’s sum up our article on the Python isinstance() function. The isinstance() is an inbuilt Python function that returns a boolean value True or False based on the specified arguments. It accepts two arguments object and classinfo. The object can be a variable or data value and the classinfo can be a list, tuple, or union of data types and class name. The function returns True if the object is an instance of classinfo, otherwise, it returns False. In the case of inheritance, the object can belong to multiple classes.

People are also reading: 

Leave a Reply

Your email address will not be published. Required fields are marked *