Python isinstance() Function

Python isinstance() is a built-in function that returns a boolean stating whether or not an object is an instance or subclass of another object. Both objects need to be supplied as arguments to the function.

python isinstance() function

Python isinstance() Syntax

isinstance(object, classinfo)

Python isinstance() takes two parameters as the argument.

  • object (required) – an object to be checked
  • classinfo (required) – A class, type or a tuple of classes, types or other tuples

So the isinstance() function checks whether or not the object is an instance or subclass of classinfo and returns True if it is, else it returns false. If classinfo is a tuple, then the function checks if the object is an instance or subclass of any element of the tuple.

Also, If classinfo is not a class, type, or tuple of classes, types or tuples, a TypeError exception is raised.

Python isinstance() Example

>>> isinstance(5,int)
>>> isinstance(5,float)
>>> isinstance('abc', str)

>>> isinstance([1,2,3], list)
>>> isinstance([1,2,3], tuple)

As you can see in above example, isinstance() only returns True if the first object is instance or subclass of the second object supplied as the argument.

>>> class Example:
       x = 1
>>> obj = Example()
>>> isinstance(obj, Example)