icon-cookie
The website uses cookies to optimize your user experience. Using this website grants us the permission to collect certain information essential to the provision of our services to you, but you may change the cookie settings within your browser any time you wish. Learn more
I agree
blank_error__heading
blank_error__body
Text direction?

Python isinstance() explained with examples

Last updated on 6 Comments

In this article, We will learn what does isinstance() function does in Python and how to use it. The Python isinstance() function is used to check whether the object or variable is an instance of the specified class type or data type.

Further reading

For example, you have a variable number = 90, and you want to check the number is an instance of an int type. You can check this using isinstance() function.

Let’s understand how to use isinstance() function with the help of a simple example.

Python isinstance()

marks = 90
result = isinstance(marks, int)
if result :
  print("Yes! given variable is an instance of type int")
else:
  print("No! given variable is not an instance of type int")

Output:

Yes! given varible is an instance of type int

Using Python isinstance(), you can do the followings:

  • Check the type of a Python variable is of a given type.
  • Verify whether a variable is a number or string.
  • Check if an object is an instance of a specified class.
  • Check whether variable or object is of dict type, list type, set type, tuple type.

The isinstance() syntax and parameter

isinstance(object, classinfo)

The isinstance() function checks if the object argument is an instance or subclass of classinfo class argument.

isinstance Parameters:

  • The isinstance() takes two arguments, and both are mandatory.
  • object:  The object/instance or variable to check. The object can be any class object or any variable name.
  • classinfo:  Class info is type name, class name or tuple of types and classes. For example, int, str, list, dict, or any user-created class.

Return Value from isinstance():

If an object or variable is of a specified type, then isinstance() return true otherwise false.

Note: If classinfo argument is not a class, type or tuple of types, a TypeError exception is raised.

isinstance() with Built-in Types

As you know, Every value (variable) in Python has a type. Different built-in types in Python are Numbers, List, Tuple, Strings, Dictionary. Most of the time you want to check the type of a value to do some operations on it. In this case, isinstance() function is useful.

In this example, we are using isinstance() function to check instance with the String type, number type, dict type, list type.

number = 80
pi = 3.14
name = "pynative.com"
complexNum = 1+2j

sampleList  = ["Eric", "Scott", "Kelly"]
studentDict = {"John":80, "Eric":70, "Donald":90}
sampleTuple = ("Sam","Developer", 10000)
sampleSet   = {11, 22, 33, 44, 55}

flag = isinstance(number, int)
print(number,'is an instance of int?', flag)

flag = isinstance(pi, float)
print(pi,'is an instance of float?', flag)

flag = isinstance(complexNum, complex)
print(complexNum, "is an instance of a complex number?", flag)

flag = isinstance(name, str)
print(name,'is an instance of String?', flag, "\n")

flag = isinstance(sampleList, list)
print(sampleList,'is instance of list?', flag)

flag = isinstance(studentDict, dict)
print(studentDict,'is instance of Dictionary?', flag)

flag = isinstance(sampleTuple, tuple)
print(sampleList,'is instance of Tuple?', flag)

flag = isinstance(sampleSet, set)
print(studentDict,'is instance of Set?', flag)

Output:

80 is an instance of int? True 
3.14 is an instance of float? True 
(1+2j) is an instance of a complex number? True 
pynative.com is an instance of String? True 

['Eric', 'Scott', 'Kelly'] is instance of list? True 
{'John': 80, 'Eric': 70, 'Donald': 90} is instance of Dictionary? True 
['Eric', 'Scott', 'Kelly'] is instance of Tuple? True 
{'John': 80, 'Eric': 70, 'Donald': 90} is instance of Set? True

Python isinstance with multiple types

You can also check the instance with multiple types. Let’s say you have a variable and you wanted to check whether it holds any numeric value or not, for example, a numeric value can be int or float. You can check this variable with multiple types. To do this, you need to mention all types in a tuple and pass it as the isinstance’s classInfo argument.

Let’s see this with an example.

firstNumber = 80
secondNumber = 55.70

result = isinstance(firstNumber, (int, float))
print(firstNumber,'is an instance of int or float?', result)

result = isinstance(secondNumber, (int, float))
print(secondNumber,'is an instance of int or float?', result)

Output:

80 is an instance of int or float? True 
55.7 is an instance of int or float? True

As you can see we mentioned two types in tuple format to check whether a given variable is a type of mentioned type in the tuple. You can add as many types in the tuple as you can want.

isinstance() with Python Class

A isinstance() function test object is of a specified class type. isinstance() is working as a comparison operator because it compares the object with the specified class type.

The isinstance result will be true if the object is an instance of the given class type:

I have created an Employee class and checking object is an instance of class Employee.

class Employee:
  
  def __init__(self, name, salary):
    self.name = name
    self.salary = salary

class Person:
  
  def __init__(self, name, sex):
    self.name = name
    self.sex = sex

emp = Employee("Emma", 11000)
per = Person("Brent", "male")

print("Checking emp object is an instance of Employee")
if isinstance(emp, Employee) :
  print("Yes! given object is an instance of class Employee\n")
else:
  print("No! given object is not an instance of class Employee")

print("Checking per object is an instance of Employee")  
if isinstance(per, Employee) :
  print("Yes! given object is an instance of class Employee")
else:
  print("No! given object is not an instance of class Employee\n")

Output:

Checking emp object is an instance of Employee
Yes! a given object is an instance of class Employee

Checking per object is an instance of Employee
No! given object is not an instance of class Employee

isinstance function with an inheritance

As we know the object of the subclass type is also a type of parent class. For example, If Car is a subclass of Vehicle then the object of Car class can be referred by either Car or Vehicle.

Then isinstance(carObject, Vehicle) will return true. The isinstance function works on the principle of the is-a relationship. The concept of an is-a relationship is based on class inheritance.

To demonstrate this, I have created two classes Developer and PythonDeveoper, Here  PythonDeveoper is a sub-class of a Developer class.

isinstance() function will also be true if the object is an instance of a subclass of the given class type:

class Developer(object): 
       
    # Constructor 
    def __init__(self, name): 
        self.name = name
    def display(self): 
        print("Developer:", self.name, "-")
   
class PythonDeveloper(Developer): 
   
    # Constructor 
    def __init__(self, name, language): 
        self.name = name
        self.language = language		
   
    def display(self): 
        print("Python Developer:", self.name, "language:", self.language, "-")
   
dev = Developer("Jhon")  # An Object of Developer 
dev.display()
result = isinstance(dev, Developer)
print("is an instance of a Developer Class? ", result, "\n")
   
pythonDev = PythonDeveloper("Eric", "Python") # An Object of PythonDeveloper 
pythonDev.display(), 
result = isinstance(pythonDev, Developer)
print("is an instance of a Developer Class? ", result)

Output:

Developer: Jhon -
is an instance of a Developer Class?  True 

Python Developer: Eric language: Python -
is an instance of a Developer Class?  True

Note: the isinstance function is beneficial for casting objects at runtime because once you get to know the given class is a subclass of a parent class you can do casting appropriately if required.

Using isinstance with Python list

As you know, a Python list is used to store multiple values at the same time. These values can be of any type like numbers, strings or any class objects.

In this section, we are performing the following operations with Python list using the isinstance() function:

  • Checking if an object is of type list in python.
  • Check if an element of a list is a list.
  • Verify if elements of a list are numbers or strings.
  • Python check if all elements of a list are the same type

Checking if an object is of type list in python

sampleList  = ["Emma", "Stevan", "Brent"]
res = isinstance(sampleList, list)
print(sampleList,'is instance of list?', res)

Output:

['Emma', 'Stevan', 'Brent'] is instance of list? True

Check if an element of a list is a list

To check if an element in the list is itself a list we can use isinstance(). For example, you have the following list and you want to check is there any element is of type list in this list.

sampleList = ['Emma', 'Stevan', ['Jordan','Donald', 'Sam']]

You need to iterate a list to check each variable’s type and if it a list type we can say that the list itself contains a list.

sampleList = ['Emma', 'Stevan', ['Jordan','Donald', 'Sam']]
for item in sampleList:
  if isinstance(item, list):
    print("Yes", item,'is list item is an instance of the given list')

Output:

Yes ['Jordan', 'Donald', 'Sam'] is list item is an instance of the list

Check if elements of a list are numbers or strings

To find numbers from the given list we need to check each element with multiple numeric types such as int, float, long and complex type using isinstance() function.

To find all string variables we can check each element type with str type.

sampleList = ['Emma', 'Stevan', 12, 45.6, 1+2j, "Eric", ]
numberList = []
stringList = []
for item in sampleList:
  if isinstance(item, (int, float, complex)):
    numberList.append(item)
  elif isinstance(item, str):
    stringList.append(item)

print("String List \n", stringList)
print("Number List \n", numberList)

Output:

String List 
 ['Emma', 'Stevan', 'Eric']
Number List 
 [12, 45.6, (1+2j)]

Using the isinstance when an Object is None

If we use isinstance with any variable or object that has a null or None value it returns false. Let see the simple example of it.

var = None

result = isinstance(var, float)
print(var,'is an instance of float?', result, "\n")

Output:

None is an instance of float? False
Measure
Measure
Related Notes
Get a free MyMarkup account to save this article and view it later on any device.
Create account

End User License Agreement

Summary | 1 Annotation
You can also check the instance with multiple types
2020/08/28 08:09