issubclass()

The built-in issubclass() function checks if a given class is a subclass of another class, returning a boolean value True or False:

Python
>>> issubclass(int, object)
True

issubclass() Signature

Python Syntax
issubclass(class, classinfo)

Arguments

Argument Description
class The class to check if it’s a subclass.
classinfo A class, tuple of classes, or a union type to check against.

Return Value

  • Returns True if the first argument, class, is a subclass (direct, indirect, or virtual) of the second argument classinfo.
  • Returns False if it’s not a subclass.
  • Raises a TypeError if classinfo isn’t a class, tuple of classes, or union type.

issubclass() Examples

With float as a subclass of object:

Python
>>> issubclass(float, object)
True

With bool as a subclass of int:

Python
>>> issubclass(bool, int)
True

With int not being a subclass of float:

Python
>>> issubclass(int, float)
False

issubclass() Common Use Cases

The most common use cases for the issubclass() function include:

  • Checking class hierarchies and inheritance relationships
  • Verifying if a class implements a particular interface or abstract base class
  • Validating input types in functions and methods that accept class objects

issubclass() Real-World Example

Say that you’re designing a plugin system where each plugin must inherit from a PluginBase class. You can use issubclass() to ensure each plugin class correctly inherits from PluginBase:

Python
>>> class PluginBase:
...     pass
...

>>> class PluginA(PluginBase):
...     pass
...

>>> class PluginB:
...     pass
...

>>> def validate_plugin(plugin_class):
...     if issubclass(plugin_class, PluginBase):
...         print(f"{plugin_class.__name__} is a valid plugin.")
...     else:
...         print(f"{plugin_class.__name__} is NOT a valid plugin.")
...

>>> validate_plugin(PluginA)
PluginA is a valid plugin.
>>> validate_plugin(PluginB)
PluginB is NOT a valid plugin.

In this example, issubclass() helps ensure that only classes inheriting from PluginBase are considered valid plugins.

Tutorial

Object-Oriented Programming (OOP) in Python

In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader