Javaexercise.com

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?

# Integer value
a = 12
r = isinstance(a,int)
print(r)
# Boolean value
a = True
r = isinstance(a,bool)
print(r)
Output:
 True
 True


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.

# List
a = [12]
r = isinstance(a,list)
print(r)
# Set
a = {12}
r = isinstance(a,set)
print(r)
# Dictionary
a = {12:"Twelve"}
r = isinstance(a,dict)
print(r)
Output:
 True
 True
 True

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.

# is instance of int type
a = [12]
r = isinstance(a,int)
print("is instance of int type? :",r)
# is instance of set type
r = isinstance(a,set)
print("is instance of set type? :",r)
# isinstance of any among (int,list,set)
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.

# int value
a = 12
r = isinstance(a,int)
print(r)
# base class of int
r = isinstance(a,object)
print(r)
# bool value
a = True
r = isinstance(a,bool)
print(r)
# parent class of bool
r = isinstance(a,int)
print(r)
# base class of bool
r = isinstance(a,object)
print(r)
Output:
 True
 True
 True
 True
 True