Python isinstance() Function

Python isinstance() function is used to check if an object is an instance of a specified class or of a subclass thereof.

Visual Representation of Basic Type Checking

Syntax

isinstance(object, classinfo)

Parameters

  1. object(required): This is the object you want to check.
  2. classinfo: This can be a type or a tuple of types.

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

Return value

It returns True if the object is an instance or subclass of the class, and False otherwise.

Example 1: Basic Type Checking 

num = 6
print(isinstance(num, int))
print(isinstance(num, float)) 

text = "Hello"
print(isinstance(text, str)) 

my_list = [10, 20, 30]
print(isinstance(my_list, list)) 

my_tuple = (5, 10, 15)
print(isinstance(my_tuple, tuple))

Output

True
False
True
True
True

Example 2: Checking Instances of Custom Classes and Tuples of Types

class App:
  GoT = 'Aegon'
 
series = App()

print(isinstance(series, App)) #'series' is an instance of 'App'
print(isinstance(series, (list, tuple))) #'series' is not a list or a tuple
print(isinstance(series, (list, tuple, App))) # 'series' is an instance of 'App'

Output

True
False
True

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.