×


Python isinstance() Function - Explained with examples

The isinstance() function in Python allows checking if an object is of the specified type. In other words, it will check if the 1st parameter is a subclass of the 2nd parameter. If it matches it will return True, otherwise, it will return False.

Here at Ibmi Media, we shall look into how to use the isinstance() function in Python.


More about the Python isinstance() Function

If an object is of the specified type, this function will return True, otherwise, it will return False.

The case the parameter is of type tuple, if the object is one of type tuple, it will return True.

It's syntax is given below:

isinstance(object, type)

Python isinstance() Function Parameter Values:

  • object: an object(Required)
  • type: class, type or tuple


Examples of using isinstance() Function

1. Have a look at the below function:

x = isinstance(1, int)
print(x)

It's Output will give :

True


2. Another example is given below:

x = isinstance(1, float)
print(x)

It's Output will give:

False


3. Another example:

class NAME:
name = "BEND"
z = NAME()
x = isinstance(z, NAME)
print(x)

The Output will give:

True


4. Check this function:

class Foo:
  a = 5
  
fooInstance = Foo()
print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))

The Output will give:

True
False
True


5. This last one:

testlist = [1, 2, 3]
print(isinstance(testlist, list))

The Output will give:

True


[Need help in fixing Python issues ? We can help you. ]


Conclusion

This article covers how to use the isinstance() function in Python. In fact, the isinstance() function checks if the object (first argument) is an instance or subclass of classinfo class (second argument).


isinstance Return Value

isinstance() returns:

  • True if the object is an instance or subclass of a class or any element of the tuple.
  • False otherwise.


If classinfo is not a type or tuple of types, a TypeError exception is raised.