Python Built-in Function isinstance:

The isinstance() is an inbuilt function in Python that returns true if the given instance is the same type specified in the parameter. However, it will return false, if there is mismatch in type.

Method signature

The signature for the isinstance() function is as shown below. Here, b is a boolean value returned by this function.

b=isinstance(object, classinfo)

Method parameters and return type

  • This method takes two parameters.
  • However, it returns a boolean value true or false.

Python Built-in Function isinstance Examples:

Example 1: For example, let us initialize a list and a set object with some numbers. Thereafter, we will use the isinstance function to check whether they are of the list and set type, respectively.

#Initializing
l=[1,2,3]
s={11,22,33}
#Using isinstance and printing
print("l is object of list - ",isinstance(l,list))
print("s is object of set - ",isinstance(s,set))

Output

l is object of list -  True
s is object of set -  True

Example 2: In the following example, we will check the instance type by providing the tuple of types. Here the output will be True, if cisinstance of either of the list, tuple, set.

#Initializing
c=[1,2,3]
#Using isinstance and printing
print("c is object of list/tuple/set - ", isinstance(c,(list,tuple,set)))

Output

c is object of list/tuple/set - True

Example 3: In this example, let’s create a user-defined class and check the instance type of it.

#Defining class and function
class student:
   def func(self):
       name="John"
       age=22
       print("Name is string type",isinstance(name,str))
       print("Age is integer type",isinstance(age,int))
#Creating class instance and calling function
t=student()
print("Is t an instance of class student?",isinstance(t,student))
t.func()

Output

Is t an instance of class student? True
Name is string type True
Age is integer type True

Conclusion

The isinstance() function checks if the object is of a specified type and accordingly returns boolean value true or false.

References

Happy Learning 🙂