isinstance() in Python With Examples

isinstance() function in Python is used to check if the passed object is an instance of the specific class or not. isinstance() is a built-in function in Python.

Python isinstance() syntax

isinstance(object, classinfo)

Returns true if the object (first argument) is an instance of the classinfo (second argument) or any of its subclass. Function returns false if object is not an object of the given type.

classinfo can also be a tuple of type objects, in that case isinstance() function returns true of object is an instance of any of the types in a passed tuple.

If classinfo is not a type or tuple of types a TypeError exception is raised.

Python isinstance() examples

1. Using isinstance() with built-in types

i = 7
s = "knocode.com"
f = 5.67
print('Is i instance of int:', isinstance(i, int))
print('Is s instance of str:', isinstance(s, str))
print('Is f instance of float:', isinstance(f, float))
print('Is s instance of float:', isinstance(s, float))

Output

Is i instance of int: True
Is s instance of str: True
Is f instance of float: True
Is s instance of float: False

2. With list, dict and tuple

t = (2, 3, 4)
l = [1, 2, 3]
d = {'Name': 'Jack', 'Age': 27}
f = 56.78
print('Is t instance of tuple:', isinstance(t, tuple))
print('Is l instance of list:', isinstance(l, list))
print('Is d instance of dict:', isinstance(d, dict))
# tuple of types
print('Is f instance of any type:', isinstance(f, (str, int, float, tuple)))

Output

Is t instance of tuple: True
Is l instance of list: True
Is d instance of dict: True
Is f instance of any type: True

3. Using isinstance() with object

That’s where isinstance() function is more useful. Since Python is an object-oriented programming language so it supports inheritance and you can create a hierarchical structure of classes where a child class inherits from a parent class.

In the example Person is the super class and Employee is the sub-class inheriting from Person. Because of this inheritance Employee object is of type Employee as well as of Person. Person object is of type Person only. Let’s verify this with the help of isinstance() function.

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

    def display_info(self):
        print('In display_info method of Person class')
        print('Name:', self.name)
        print('Age:', self.age)


class Employee(Person):
    def __init__(self, person_id, department, name, age):
        super().__init__(name, age)
        self.person_id = person_id
        self.department = department

    def display_info(self):
        super().display_info()
        print('In display_info method of Employee class')
        print('Id:', self.person_id)
        print('Department:', self.department)

e = Employee(1, "IT", "Michael Weyman", 42)
p = Person("Amit Tiwari", 34)
print('e is an instance of Employee', isinstance(e, Employee))
print('e is an instance of Person', isinstance(e, Person))
print('p is an instance of Person', isinstance(p, Person))
print('p is an instance of Employee', isinstance(p, Employee))

Output

e is an instance of Employee True
e is an instance of Person True
p is an instance of Person True
p is an instance of Employee False

You might be thinking all this is ok but what benefit do I get by just checking whether isinstance() returns true or false.

Python is a dynamically typed language and type is implicitly assigned depending on the value passed. This function comes handy if you want to be sure if the called method is present for an object or not. Here note that if you call a method that is not present for the object AttributeError is raised at runtime.

Consider the following program-

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

    def display_info(self):
        print('In display_info method of Person class')
        print('Name:', self.name)
        print('Age:', self.age)


class Employee(Person):
    def __init__(self, person_id, department, name, age):
        super().__init__(name, age)
        self.person_id = person_id
        self.department = department

    def display_info(self):
        super().display_info()
        print('In display_info method of Employee class')
        print('Id:', self.person_id)
        print('Department:', self.department)


class Test:
    pass


def call_method(o):
    o.display_info()


e = Employee(1, "IT", "Michael Weyman", 42)
call_method(e)
t = Test()
call_method(t)

Another class Test is added and there is a method call_method which takes an object as argument and calls display_info() method on that object. For object of class Employee it will work fine but calling display_info() method on object of class T results in AttributeError.

Output

in call_method
    o.display_info()
AttributeError: 'Test' object has no attribute 'display_info'
In display_info method of Person class
Name: Michael Weyman
Age: 42
In display_info method of Employee class
Id: 1
Department: IT

In such scenario where you want to be sure if object is of certain type and call to the method is valid you can check the type of the object using isinstance(). You can change call_method to include isinstance() as given below-

def call_method(o):
    if isinstance(o, Person):
        o.display_info()

Related Posts

That’s all for the topic isinstance() in Python With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.