Python issubclass(): Check if a Class is a Subclass of Another

The issubclass() function checks if a class is a subclass of another class or a tuple of classes. It’s useful for verifying inheritance, designing flexible code, and ensuring class relationships.

Example

class Animal:
    pass

class Dog(Animal):
    pass

print(issubclass(Dog, Animal))  
# Output: True

Since Dog inherits from Animal, issubclass() returns True.

Syntax

issubclass(class, class_or_tuple)
  • class → The class to check.
  • class_or_tuple → The parent class(es) to compare against.
  • ReturnsTrue if class is a subclass of class_or_tuple, else False.

1. Checking Multiple Parent Classes

A class can be checked against multiple parent classes using a tuple.

class Bird:
    pass

class Sparrow(Bird):
    pass

print(issubclass(Sparrow, (Animal, Bird)))  
# Output: True

This is useful when checking multiple possible parents.

2. Using issubclass() with Built-in Types

print(issubclass(bool, int))  
# Output: True

In Python, bool is a subclass of int.

3. Checking for Direct vs. Indirect Subclasses

issubclass() works with multiple inheritance levels.

class Mammal(Animal):
    pass

class Human(Mammal):
    pass

print(issubclass(Human, Animal))  # True (Inherited from Mammal)
print(issubclass(Human, Mammal))  # True (Direct parent)
print(issubclass(Human, Dog))     # False (No relation)

This traces class inheritance chains.

4. Avoiding Errors with issubclass()

If the first argument is not a class, Python raises a TypeError.

print(issubclass(10, int))  
# TypeError: issubclass() arg 1 must be a class

Make sure you’re passing classes, not instances.

Key Notes

  • Checks if a class inherits from another class.
  • Supports multiple parents with tuples.
  • Works with built-in types (e.g., bool is a subclass of int).
  • Validates class relationships in complex hierarchies.

By using issubclass(), you can verify class inheritance, improve code flexibility, and handle object-oriented structures effectively. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top