Skip to content

How to Check If an Object Is an Instance of a Class in Python

Learn how to verify an object's type in Python using isinstance() for inheritance-aware checks and type() for exact class matching, with practical examples for OOP type checking.

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).

class Dog:
    species = "Canis familiaris"

    def __init__(self, name, age):
        self.name = name
        self.age = age

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'>

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"

if isinstance(buddy, Dog):
    print("Buddy is a Dog.")

if isinstance(name, str):
    print(f"'{name}' is a string.")

Output:

Buddy is a Dog.
'Buddy' is a string.

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()

if type(buddy) is Dog:
    print("Buddy is exactly a Dog.")
    

Output:

Buddy is exactly a Dog.

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()

print(f"Is Sparky a Dog?             {isinstance(sparky, Dog)}")
print(f"Is Sparky a GermanShepherd?  {isinstance(sparky, GermanShepherd)}")

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:

  1. Use isinstance(obj, Class) for almost all use cases. It supports inheritance, making your code flexible and compatible with subclasses.
  2. Use type(obj) is Class only when you need to strictly differentiate between a parent class and a subclass (e.g., for debugging or specific factory logic).
Navigation