Python isinstance() Method
Python isinstance() method is a built-in method. It returns True if object (first argument) is an instance of the given type, else returns False. Type (the second argument) can be a class, subclass or a tuple of type objects.
Signature
isinstance(object, classinfo)
Parameter |
Description |
object |
Object of a class or type which is to be checked. |
classinfo |
Class, Type or tuple of classes. |
Return Value
It returns a boolean value either True or False.
Error: It returns an error (TypeError), if classinfo is not a standard Python type.
Python isinstance() Method Example
Let’s first understand, how this method works and what does it return?
a = 12
r = isinstance(a,int)
print(r)
a = True
r = isinstance(a,bool)
print(r)
Python isinstance() Method Example
You can also use this method to check class and object association for other objects like: list or set. See the below example.
a = [12]
r = isinstance(a,list)
print(r)
a = {12}
r = isinstance(a,set)
print(r)
a = {12:"Twelve"}
r = isinstance(a,dict)
print(r)
Python isinstance() Method Example: Using Tuple
If you are not sure about the type (class) of an object, you can pass tuple of types to provide possible match. See the below example.
a = [12]
r = isinstance(a,int)
print("is instance of int type? :",r)
r = isinstance(a,set)
print("is instance of set type? :",r)
r = isinstance(a,(int,list,set))
print("is instance of any among (int,list,set)? :",r)
Output:
is instance of int type? : False
is instance of set type? : False
is instance of any among (int,list,set)? : True
In the above example, we passed multiple types as a tuple and method returns True because of type list is present in the tuple.
Python isinstance() Method Example: Using Class Hierarchy
In other scenario, this method can return True if the type (class) is a base class of the object. Like: int is a base class of bool class and object is a base class of int. See the below example.
a = 12
r = isinstance(a,int)
print(r)
r = isinstance(a,object)
print(r)
a = True
r = isinstance(a,bool)
print(r)
r = isinstance(a,int)
print(r)
r = isinstance(a,object)
print(r)
Output:
True
True
True
True
True