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() 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)
True
>>> isinstance(5,float)
False
>>> isinstance('abc', str)
True
>>> isinstance([1,2,3], list)
True
>>> isinstance([1,2,3], tuple)
False
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)
True