How to Use isinstance() and issubclass() Functions

Checking the type of an object or verifying class inheritance is something I do daily when building complex Python applications.

Whether I am validating data from a web form or ensuring a function receives the correct object type, these built-in functions are my go-to tools.

In this tutorial, I will show you exactly how isinstance() and issubclass() work and when you should use one over the other.

Why Type Checking Matters in Python

Python is a dynamically typed language, which gives us a lot of flexibility when writing code.

However, this flexibility can lead to unexpected errors if a variable doesn’t contain the type of data your logic expects.

I have found that using explicit type checking makes my code more readable and significantly easier to debug.

The Python isinstance() Function

The isinstance() function is used to check if an object is an instance of a specific class or a tuple of classes.

It returns True if the object matches the type, and False otherwise. It also accounts for inheritance, which is a major advantage.

Basic Syntax of isinstance()

The syntax is easy: isinstance(object, classinfo).

The classinfo can be a single class, a type, or a tuple containing multiple classes.

Method 1: Check Basic Data Types

I often use this method when I need to ensure that a user-provided value, like a Zip Code, is actually an integer.

In the USA, while Zip Codes are often handled as strings to preserve leading zeros, many internal calculations require them to be numeric.

# Checking if a variable is an integer
zip_code = 90210

if isinstance(zip_code, int):
    print("The Zip Code is a valid integer.")
else:
    print("Invalid Zip Code format.")

# Output: The Zip Code is a valid integer.

I executed the above example code and added the screenshot below.

isinstance() and issubclass() Functions

Method 2: Use a Tuple for Multiple Types

Sometimes, a variable could legitimately be one of several types. I use a tuple within isinstance() to check for this in a single line.

For example, an “Annual Income” field might accept either a whole number (int) or a decimal (float).

# Checking against multiple types
annual_income = 75000.50

if isinstance(annual_income, (int, float)):
    print(f"Income of {annual_income} is a valid numeric value.")
else:
    print("Please enter a numeric value for income.")

# Output: Income of 75000.5 is a valid numeric value.

I executed the above example code and added the screenshot below.

How to Use isinstance() and issubclass() Functions

Method 3: isinstance() with Custom Classes

When working with Object-Oriented Programming (OOP), I use isinstance() to verify that I’m working with specific objects.

Imagine a system managing the US Government branches. I can verify if an object belongs to a specific branch class.

class GovernmentBranch:
    pass

class Legislative(GovernmentBranch):
    pass

class Executive(GovernmentBranch):
    pass

# Create an instance
senate = Legislative()

# Check if senate is an instance of Legislative
print(isinstance(senate, Legislative))  # True

# Check if senate is an instance of the parent class
print(isinstance(senate, GovernmentBranch))  # True

The Python issubclass() Function

While isinstance() checks an object, issubclass() is used to check if a class is a derived subclass of another class.

I use this when I am building frameworks or plugins where I need to ensure a class follows a specific structure.

Basic Syntax of issubclass()

The syntax is: issubclass(class, classinfo).

Method 1: Check Direct Inheritance

In the US legal system, there are various types of courts. I can use issubclass() to verify that a FederalCourt is indeed a type of Court.

class Court:
    pass

class FederalCourt(Court):
    pass

class StateCourt(Court):
    pass

# Verify inheritance
print(issubclass(FederalCourt, Court))  # True
print(issubclass(StateCourt, Court))    # True
print(issubclass(Court, FederalCourt))  # False

Method 2: Check Against Multiple Parent Classes

Similar to isinstance(), you can provide a tuple of classes to issubclass(). It returns True if the class is a subclass of any item in the tuple.

class Transport:
    pass

class Aviation(Transport):
    pass

class DeltaAirLines(Aviation):
    pass

# Check if DeltaAirLines belongs to either Aviation or Transport
print(issubclass(DeltaAirLines, (Aviation, Transport)))  # True

I executed the above example code and added the screenshot below.

Use isinstance() and issubclass() Functions

Key Differences Between isinstance() and issubclass()

It is easy to get these two confused, but I follow one simple rule to remember the difference.

isinstance() looks at an instance (an object), while issubclass() looks at the class definition itself.

Featureisinstance()issubclass()
First ArgumentAn object (instance)A class
Second ArgumentA class or tuple of classesA class or tuple of classes
PurposeChecks if object is an instanceChecks inheritance relationship

Handle Real-World Data Validation

In my experience, using these functions is critical when dealing with API responses or external data files.

Suppose you are processing a list of U.S. states and their populations. You want to ensure the data is formatted correctly before performing calculations.

def process_state_data(data):
    # Ensure data is a dictionary
    if not isinstance(data, dict):
        return "Error: Data must be a dictionary."
    
    state_name = data.get("name")
    population = data.get("population")

    # Validate types
    if isinstance(state_name, str) and isinstance(population, int):
        print(f"Processing {state_name} with a population of {population}.")
    else:
        print("Invalid data types found in dictionary.")

# Example usage
ny_data = {"name": "New York", "population": 8336000}
process_state_data(ny_data)

Advanced Usage: The type() Function vs isinstance()

Newer developers often ask me why I don’t just use type(obj) == int.

While type() works, it does not support inheritance. If you have a subclass, type() will return False when comparing it to the parent class.

isinstance() is the “Pythonic” way because it respects the “is-a” relationship in OOP.

class Employee:
    pass

class Manager(Employee):
    pass

m = Manager()

# type() check
print(type(m) == Employee)  # False (This is usually not what you want)

# isinstance() check
print(isinstance(m, Employee))  # True (This is correct)

Practical Application: Financial Calculations

In the US, tax rates can vary. If I am writing a function to calculate sales tax, I need to ensure the rate is a float or an integer.

Using these checks prevents the program from crashing if a string like “8%” is passed instead of 0.08.

def calculate_tax(amount, rate):
    if not isinstance(amount, (int, float)) or not isinstance(rate, (int, float)):
        raise ValueError("Both amount and rate must be numeric.")
    
    return amount * rate

try:
    # Example for a California sales tax calculation
    total = calculate_tax(100, 0.0725)
    print(f"Total Tax: ${total}")
except ValueError as e:
    print(e)

Best Practices I Follow

When using these functions in production-level code, I follow a few internal guidelines:

  1. Avoid Over-checking: Don’t check types for every single variable; it can slow down your code. Use it at the boundaries of your application (like user input).
  2. Prefer isinstance over type: Always use isinstance() unless you specifically need to exclude subclasses.
  3. Use Descriptive Errors: If a type check fails, raise a TypeError with a helpful message.

In this tutorial, we looked at how to use isinstance() and issubclass() to manage types and inheritance in Python.

These tools are essential for writing robust, error-free code, especially when dealing with complex data structures or class hierarchies.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.