Python isinstance() function is used to check if an object is an instance of a specified class or of a subclass thereof.
Syntax
isinstance(object, classinfo)
Parameters
- object(required): This is the object you want to check.
- 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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.