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 specified type, the isinstance() function return True, otherwise, false.

In the next few sections, we will be explaining more about this function.

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.

Examples

Now, let's understand the working of isinstance() function with the help of examples −

Example 1

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 2

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 3

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 4

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