Python isinstance() Function



The Python isinstance() function is used to determine whether the specified object is an instance of a specific class or its subclass.

Also, we can use this function for type checking. If the specified object is of a specified type, the isinstance() function returns True, otherwise, false.

The isinstance() is one of the built-in functions and don't need to import any module to use this.

Syntax

The following is the syntax for the python isinstance() function.

isinstance(object, type)

Parameters

The following are the parameters of the Python isinstance() function −

  • object − This parameter specifies an object such as string, int, float or long.

  • type − This parameter specifies a class or type, against which object is needed to be checked.

Return Value

The Python isinstance() function returns a Boolean value.

isinstance() Function Examples

Practice the following examples to understand the use of isinstance() function in Python:

Example: Use of isinstance() Function

The following is an example of the python isinstance() function. In this, we have defined a numeric value and, trying to verify whether it is of type integer.

nums = 5
output = isinstance(nums, int)
print("The given number is instance of integer:", output)

On executing the above program, the following output is generated −

The given number is instance of integer: True

Example: isinstance() Function With Multiple Type Arguments

We can also pass multiple type arguments to the isinstance() function. Here, we have defined a string and checked if it is of type string and bytes.

strName = "Tutorialspoint"
output = isinstance(strName, (str, bytes))
print("The given string is instance of string:", output)

The following is the output obtained by executing the above program −

The given string is instance of string: True

Example: Checking Subclass of a Class Using isinstance() Function

In the following example, we have defined a class and its subclass. Then, with the help of isinstance() function, we check whether it is a subclass of the specified class.

class Seasons:
   pass

class Spring(Seasons):
   pass

springObj = Spring()
output = isinstance(springObj, Seasons)
print("The given object is instance of Seasons class:", output)

The following output is obtained by executing the above program -

The given object is instance of Seasons class: True

Example: Checking NoneType Object Using isinstance() Function

The isinstance() function also allows us to check whether an object is of NoneType as illustrated in the below example.

varNone = None
output = isinstance(varNone, type(None))
print("The given variable is instance of None:", output)

The above program, on executing, displays the following output -

The given variable is instance of None: True
python_built_in_functions.htm
Advertisements