Python Reference ยท Built-in Functions
Python issubclass() function
Reference for Python issubclass(): test whether a class derives from another, the difference from isinstance(), tuples of classes, ABCs and TypeError cases.
The issubclass() function returns True if a class is a subclass of another class. Every class counts as a subclass of itself, and the relationship is transitive: a class derived from a derived class is a subclass of the original as well.
It works with classes, not instances. If you have an object, use isinstance(); if you have a class and need to know how it relates to another, use issubclass(). It is handy in plugin systems and factories that receive classes as arguments.
print(issubclass(bool, int)) # True
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
issubclass(cls, classinfo)
| Name | Description |
|---|---|
cls |
The class to test. It must be a class. |
classinfo |
A class, a tuple of classes, or a union such as `int |
Return value: True or False.
Raises: TypeError if cls is not a class (for example an instance or a string), or if classinfo is invalid.
Usage notes
- Reflexive.
issubclass(C, C)isTrue. Compare withcls is Basewhen you want to exclude the class itself. - Not for instances.
issubclass(5, int)raisesTypeError; useisinstance(5, int). When the input might not be a class, checkisinstance(x, type)first, as in the second example. - Tuples.
issubclass(cls, (A, B))is true ifclsderives from either. - Abstract base classes can claim subclasses without inheritance (virtual subclasses via
register(), or__subclasshook__). That is howissubclass(list, Sequence)is true althoughlistdoes not inherit fromSequence. - Protocols. A
Protocolclass can only be used here if it is decorated with@runtime_checkable, and non-method protocols are not allowed. - Method resolution order. The inheritance chain that
issubclass()follows is visible incls.__mro__. - Generics are not allowed.
issubclass(list, list[int])raisesTypeError.