How to Check If an Object Is an Instance of a Class in Python
In Object-Oriented Programming (OOP), it is often necessary to verify the type of an object before performing operations on it. This is known as type checking or introspection. Python provides two primary ways to do this: the isinstance() function and the type() function.
This guide explains how to define classes, create instances, and effectively determine if an object belongs to a specific class or its hierarchy.
Understanding Classes and Instances
Before checking types, it is important to understand the relationship between a Class (the blueprint) and an Instance (the object built from the blueprint).
# Define the Blueprint
class Dog:
species = "Canis familiaris"
def __init__(self, name, age):
self.name = name
self.age = age
# Create Instances
buddy = Dog("Buddy", 9)
miles = Dog("Miles", 4)
print(f"Object: {buddy}")
print(f"Class: {Dog}")
Output:
Object: <__main__.Dog object at 0x7cacaa4adc10>
Class: <class '__main__.Dog'>
Method 1: Using isinstance() (Recommended)
The standard, "Pythonic" way to check an object's type is using the isinstance() built-in function. It checks if an object is an instance of a class or any subclass thereof.
Syntax: isinstance(object, classinfo)
class Dog:
pass
buddy = Dog()
name = "Buddy"
# ✅ Correct: Checking if buddy is a Dog
if isinstance(buddy, Dog):
print("Buddy is a Dog.")
# ✅ Correct: Checking built-in types
if isinstance(name, str):
print(f"'{name}' is a string.")
Output:
Buddy is a Dog.
'Buddy' is a string.
isinstance() can accept a tuple of classes. This returns True if the object matches any of the classes in the tuple.
isinstance(val, (int, float)) checks if val is a number.
Method 2: Using type() (Exact Match)
If you need to check if an object is exactly a specific class, excluding subclasses, you can compare the object's type directly using type().
class Dog:
pass
buddy = Dog()
# ⛔️ Less Flexible: Comparing types directly
# This ignores inheritance (see Section 4)
if type(buddy) is Dog:
print("Buddy is exactly a Dog.")
# Alternatively: type(buddy) == Dog
Output:
Buddy is exactly a Dog.
Using type() breaks the principle of Polymorphism. In most applications, you want your code to accept a specific class and any specialized version (subclass) of it. Therefore, isinstance() is usually preferred over type().
Handling Inheritance
The key difference between isinstance() and type() becomes apparent when inheritance is involved.
Let's create a GermanShepherd class that inherits from Dog.
class Dog:
pass
class GermanShepherd(Dog):
pass
sparky = GermanShepherd()
# ✅ isinstance() respects inheritance
# Sparky IS a GermanShepherd, but he is ALSO a Dog.
print(f"Is Sparky a Dog? {isinstance(sparky, Dog)}")
print(f"Is Sparky a GermanShepherd? {isinstance(sparky, GermanShepherd)}")
# ⛔️ type() is strict
# Sparky is exactly a GermanShepherd, so checking against Dog returns False.
print(f"Is type(sparky) == Dog? {type(sparky) is Dog}")
Output:
Is Sparky a Dog? True
Is Sparky a GermanShepherd? True
Is type(sparky) == Dog? False
Conclusion
To check if an object is an instance of a class in Python:
- Use
isinstance(obj, Class)for almost all use cases. It supports inheritance, making your code flexible and compatible with subclasses. - Use
type(obj) is Classonly when you need to strictly differentiate between a parent class and a subclass (e.g., for debugging or specific factory logic).