Last Updated : 11 Jul, 2025
isinstance() is a built-in Python function that checks whether an object or variable is an instance of a specified type or class (or a tuple of classes), returning True if it matches and False otherwise, making it useful for type-checking and ensuring safe operations in dynamic code. Example:
Python
x = 10
print(isinstance(x, int)) # x is int
class Animal: pass
dog = Animal()
print(isinstance(dog, Animal)) # dog is Animal
Explanation:
isinstance(obj, classinfo)
Parameters:
Returns:
Raises: TypeError if classinfo is not a valid class or type.
Examples of isinstance()Example 1: In this example, we use isinstance() to check if an integer and a list are instances of the int or str types.
Python
a = 5
b = [10,20,37]
print(isinstance(a, int))
print(isinstance(b, list))
print(isinstance(b, (int, list,str)))
Explanation:
Example 2: In this example, we check if an object is an instance of a specific class or its parent class.
Python
class Animal: pass
class Dog(Animal): pass
dog = Dog()
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
Explanation:
Example 3: In this example, we check if an object is an instance of a specific type, such as a Python string or a dictionary.
Python
a = "Hello"
print(isinstance(a, str))
b = {"apple": 1}
print(isinstance(b, dict))
Explanation:
Example 4: In this example, we check if an object is an instance of a class or its derived class.
Python
class MyClass:
def method(self): return "Hello"
obj = MyClass()
print(isinstance(obj.method(), str))
Explanation: isinstance(obj.method(), str) returns True as obj.method() returns the string "Hello".
The following table highlights the differences between the isinstance() and type() methods, both used for type checking. Knowing when to use each helps write more efficient and reliable code.
isinstance()
type()
Syntax: isinstance(object, class) Syntax: type(object)It checks if an object is of a specific class type
It returns the class type of an object
It can check if the object belongs to a class and its subclasses
It cannot deal with inheritance
It is faster as compared to type() It is slower than isinstance() It returns either True or False It returns the type of the object It can check for multiple classes at a time It cannot do this Example: isinstance(10, (int, str)) Example: type(10)RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4