How to Use issubclass in Python: Syntax and Examples
Use
issubclass(class, classinfo) to check if class is a subclass of classinfo or a tuple of classes. It returns True if it is, otherwise False.Syntax
The issubclass() function takes two arguments:
class: The class you want to check.classinfo: A class or a tuple of classes to check against.
It returns True if class is a subclass of classinfo, otherwise False.
python
issubclass(class, classinfo)Example
This example shows how to use issubclass() to check class inheritance between custom classes and built-in classes.
python
class Animal: pass class Dog(Animal): pass class Cat(Animal): pass print(issubclass(Dog, Animal)) # True because Dog inherits Animal print(issubclass(Cat, Dog)) # False because Cat does not inherit Dog print(issubclass(Dog, (Animal, Cat))) # True because Dog inherits Animal print(issubclass(int, object)) # True because int inherits object print(issubclass(str, (int, float))) # False because str is not subclass of int or float
Output
True
False
True
True
False
Common Pitfalls
Common mistakes when using issubclass() include:
- Passing an instance instead of a class as the first argument causes a
TypeError. - Forgetting that
classinfocan be a tuple of classes to check multiple inheritance. - Assuming
issubclass()works with instances instead of classes.
python
class A: pass class B(A): pass obj = B() # Wrong: passing instance instead of class try: print(issubclass(obj, A)) except TypeError as e: print(f"Error: {e}") # Right: pass class print(issubclass(B, A))
Output
Error: issubclass() arg 1 must be a class
True
Quick Reference
| Usage | Description |
|---|---|
| issubclass(A, B) | Returns True if A is subclass of B |
| issubclass(A, (B, C)) | Returns True if A is subclass of B or C |
| issubclass(instance, B) | Raises TypeError, first argument must be a class |
| issubclass(A, object) | Always True for new-style classes |
Key Takeaways
Use issubclass() to check if one class inherits from another.
The first argument must be a class, not an instance.
The second argument can be a class or a tuple of classes.
issubclass() returns True if the first class is a subclass of the second.
Passing an instance instead of a class raises a TypeError.