Note
Python - isinstance() - Check object type and subclass
Overview of the Python isinstance() Function: Check Object Type and Subclass with Examples
isinstance(object, class) is a built-in Python function that checks if an object is an instance of a specified class
or a subclass of that class. It returns a boolean value. True if the object is an instance of the
given class or a subclass, and False if it isn't.
The function takes two arguments.
The object that we want to check, and the class (or a tuple of classes) to check for.
When providing a tuple as a second argument, the syntax looks like that - isinstance(object, (class_A, class_B, ...))
Take a look at the examples below:
Using isinstance() with Custom Classes
class Animal:
pass
class Mammal(Animal):
pass
class Reptile(Animal):
pass
class Dog(Mammal):
pass
animal = Animal()
mammal = Mammal()
reptile = Reptile()
dog = Dog()
print(isinstance(animal, Animal)) # True
print(isinstance(mammal, Animal)) # True (Mammal is a subclass of Animal)
print(isinstance(reptile, Mammal)) # False
print(isinstance(dog, Mammal)) # True (Dog is a subclass of Mammal)
print(isinstance(dog, (Mammal, Reptile))) # True (Dog is an instance of Mammal and Mammal is in the tuple)
Output:
True
True
False
True
True
Using isinstance() with Built-In Types
Using isinstance() can be helpful when you want to ensure that an object is of a certain type before
performing operations on it.
Remember that isinstance() also works with built-in Python types:
number = 42
text = "Hello, World!"
my_list = [1, 2, 3]
print(isinstance(number, int)) # True
print(isinstance(text, str)) # True
print(isinstance(my_list, list)) # True
print(isinstance(number, (int, float))) # True (the number is an instance of int, which is in the tuple)
Output:
True
True
True
True
To summarize, isinstance() is a function that allows you to check if an object is an instance of a
specific class or a subclass.
Key Points to Remember about the isinstance() Function
-
Checks Class Hierarchy: Returns
Truefor both classes and subclasses of the provided type. -
Supports Multiple Types: Use a
tuplefor checking against multiple classes at once. -
Works with Built-In Types: Handles Python's built-in types like
int,str,list, etc. -
Boolean Return: Always returns a
TrueorFalsevalue, making it easy to use in conditions.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!