Python isinstance() Method


isinstance() function to determine if an object is a known type, similar to type().

Related course: Complete Python Programming Course & Exercises

syntax

The following is the syntax of the isinstance() method:

isinstance(object, classinfo)
  • object -- the instance object.
  • classinfo -- can be a direct or indirect class name, a base type or a tuple with them.

Return value Returns True if the object is of the same type as argument two (classinfo), otherwise False.

isinstance example

An example of using the isinstance function is shown below.

>>>a = 2
>>> isinstance (a,int)
True
>>> isinstance (a,str)
False
>>> isinstance (a,(str,int,list)) # is one of the tuple that returns True
True

You can use isinstance in an if statement or function like this:

def trim(a):
    if not isinstance(a,str):
        raise TypeError('argument must be str type')
    if a=='':
        return a

Direct on code.

class BaseC:
    pass

class TestC(BaseC , str):
    pass

# type() does not consider a child class to be a type of the parent class
print(type( TestC()) == BaseC)
print(type( TestC()) == TestC)

# The isinstance() method considers a child class object to be an instance of the parent class
print(isinstance( TestC(),BaseC) )
print(isinstance( TestC(),TestC) )

This works for functions and classes imported from modules too

>>> import datetime
>>> now=datetime.datetime.now()
>>> isinstance(now, datetime.datetime)

type() and isisinstance() functions

type() does not consider a child class to be a kind of parent class

The isinstance() method considers: a child class object to be an instance of the parent class

The program below shows the differences:

>>> isinstance(12, int)
True
>>> type(12)
<class 'int'>

>>> isinstance(3.5, float)
True
>>> type(3.5)
<class 'float'>

>>> isinstance("123 OK",str)
True
>>> type("123 OK")
<class 'str'>