The isinstance(object, classinfo) function verifies whether an object is an instance of a specified class or any subclass derived from it, returning True or False.
Polymorphic Type Checking: Unlike exact type equality via type(), isinstance() fully respects object-oriented inheritance and polymorphism. The second parameter can be a single class or a tuple of candidate types evaluated with logical OR matching. To compare classes against each other rather than instances, use issubclass(). For related inspection tools, explore callable(), vars(), and getattr().
The isinstance() function accepts an object instance and a target type or tuple of types:
is_match = isinstance(object, classinfo)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
object |
Any Python entity | The target instance or value being inspected. |
classinfo |
type, tuple of types, or UnionType |
A class, type, or tuple containing classes. Union syntax (e.g. int | str) is also supported. |
| Return Value | bool |
Returns True if object is an instance of classinfo or a subclass thereof; otherwise False. |
Python natively validates standard built-in types:
my_number = 34
my_str = "plus2net"
my_list = ["a", "b", "c"]
my_tuple = ("x", "y", "z")
my_dict = {1: "One", 2: "Two"}
my_set = {"one", "two"}
print("Integer check:", isinstance(my_number, int))
print("String check:", isinstance(my_str, str))
print("List check:", isinstance(my_list, list))
print("Tuple check:", isinstance(my_tuple, tuple))
print("Dictionary check:", isinstance(my_dict, dict))
print("Set check:", isinstance(my_set, set))
Output:
Integer check: True
String check: True
List check: True
Tuple check: True
Dictionary check: True
Set check: True
Verify whether an object belongs to any of several allowed types by passing a tuple:
data_item = "plus2net"
# 1. Single type mismatch
print("Is integer:", isinstance(data_item, int))
# 2. Tuple of allowed types (logical OR)
print("Is int or str:", isinstance(data_item, (int, str)))
# 3. Numeric verification (int or float)
score = 98.5
print("Is numeric:", isinstance(score, (int, float)))
Output:
Is integer: False
Is int or str: True
Is numeric: True
A derived subclass instance is automatically considered an instance of its parent classes:
class Animal:
home = "Jungle"
def __init__(self, name: str):
self.name = name
class Wild(Animal):
weight = 200
class Bird(Wild):
species = "Eagle"
tiger = Animal("Alex")
lion = Wild("Tom")
# Parent instance is NOT an instance of child class
print("tiger is Animal:", isinstance(tiger, Animal))
print("tiger is Wild: ", isinstance(tiger, Wild))
# Child instance IS an instance of parent class
print("lion is Wild: ", isinstance(lion, Wild))
print("lion is Animal: ", isinstance(lion, Animal))
Output:
tiger is Animal: True
tiger is Wild: False
lion is Wild: True
lion is Animal: True
isinstance() vs. type(): Why isinstance is Preferred 🔝type(obj) is Class checks exact identity without inheritance; isinstance() supports polymorphism:
| Feature | isinstance(obj, Class) |
type(obj) is Class |
|---|---|---|
| Inheritance Support | Yes (recognizes derived subclasses) | No (matches exact class only) |
| Tuple Matching | Yes: (int, float, str) |
No (requires explicit chained comparisons) |
| Boolean Nuance | isinstance(True, int) is True |
type(True) is int is False |
class Base:
pass
class Derived(Base):
pass
obj = Derived()
print("isinstance(obj, Base):", isinstance(obj, Base))
print("type(obj) is Base: ", type(obj) is Base)
Output:
isinstance(obj, Base): True
type(obj) is Base: False
Use collections.abc to check whether objects conform to abstract roles:
import collections.abc
items = [1, 2, 3]
mapping = {"a": 10}
print("List is Sequence:", isinstance(items, collections.abc.Sequence))
print("List is Iterable:", isinstance(items, collections.abc.Iterable))
print("Dict is Mapping: ", isinstance(mapping, collections.abc.Mapping))
Output:
List is Sequence: True
List is Iterable: True
Dict is Mapping: True
Normalize inputs supplied as a single value or collection:
def normalize_tags(raw_input) -> list[str]:
if isinstance(raw_input, str):
return [raw_input.strip()]
elif isinstance(raw_input, (list, tuple, set)):
return [str(t).strip() for t in raw_input]
raise TypeError("Tags must be a string or collection of strings")
print("From string:", normalize_tags("python"))
print("From set: ", normalize_tags({"web", "api"}))
Output:
From string: ['python']
From set: ['api', 'web']
Route stream events based on class hierarchy:
class Event: pass
class PaymentEvent(Event): pass
class AlertEvent(Event): pass
def handle_event(ev: Event) -> str:
if isinstance(ev, PaymentEvent):
return "Processing financial settlement"
elif isinstance(ev, AlertEvent):
return "Dispatching security alert"
return "Unknown event type"
print(handle_event(PaymentEvent()))
print(handle_event(AlertEvent()))
Output:
Processing financial settlement
Dispatching security alert
bool is a subclass of int. Consequently, isinstance(True, int) evaluates to True! If you need strictly integers and not booleans, add and not isinstance(val, bool).
flag = True
print("isinstance(True, int):", isinstance(flag, int))
print("Strict integer check:", isinstance(flag, int) and not isinstance(flag, bool))
Output:
isinstance(True, int): True
Strict integer check: False
Practice polymorphic validation, ABCs, and type verification in our companion Jupyter Notebook:
Explore interactive code cells, test virtual ABC registrations, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks in Python to verify isinstance() mechanics:
def test_isinstance_mechanics():
class Parent: pass
class Child(Parent): pass
p = Parent()
c = Child()
assert isinstance(c, Child) is True
assert isinstance(c, Parent) is True
assert isinstance(p, Child) is False
assert isinstance("text", (int, str)) is True
assert isinstance(True, int) is True
print("All isinstance() unit assertions passed! 100% verified.")
test_isinstance_mechanics()
Output:
All isinstance() unit assertions passed! 100% verified.
Checks if a class derives from another class or tuple of classes.
Returns the exact type of an object without inheritance traversal.
Verifies whether an object or class constructor can be invoked.
Returns the __dict__ mapping for an object or module namespace.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.