Python isinstance()

In this post, we will see about python isinstance function.
Python isinstance checks if object an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass.If object is not instance of classinfo, then it returns false else returns true.


Syntax

object: object which you want to check
classinfo: a tuple of type objects, return true if object is an instance of any of the types.


Return

It returns true if object is an instance of any of the types in classinfo tuple


Example

Let’s see a very simple example:

l=[1,2,3,4] print("is l instance of list: ",isinstance(l,(list))) print("is l instance of dict: ",isinstance(l,(dict))) print("is l instance of dict or list: ",isinstance(l,(dict,list))) f=4.3 print("is f instance of int: ",isinstance(f,(int))) print("is f instance of int or float: ",isinstance(f,(int,float)))

Output:

is l instance of list: True
is l instance of dict: False
is l instance of dict or list: True
is f instance of int: False
is f instance of int or float: True

Let’s check with custom types.

class Country: name = 'India' population = 10000 country = Country() print('is country instance of list or dict:', isinstance(country,(list,dict))) print('is country instance of list or dict or Country:', isinstance(country,(list,dict,Country)))

Output:

is country instance of list or dict: False
is country instance of list or dict or Country: True

that’s all about python isinstance function.

Leave a Reply

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