Python 3 reference · Built-in Functions
Python isinstance() Function
Return True if an object is an instance of a class, one of its subclasses, or any class in a tuple or union of classes.
Python 3 Since 3.0
Syntax
isinstance(object, classinfo)
Parameters
| Parameter | Description |
|---|---|
object |
The value to check. |
classinfo |
A class, a tuple of classes, or a union such as int | float. |
Return value
True or False.
Examples
print(isinstance(5, int), isinstance(5.0, int))
print(isinstance(5.0, (int, float)))
print(isinstance(5.0, int | float))
Output
True False True True
print(isinstance(True, int)) # bool is a subclass of int
print(type(True) is int)
Output
True False
def total(value):
if isinstance(value, (list, tuple)):
return sum(value)
return value
print(total([1, 2, 3]), total(10))
Output
6 10
isinstance() vs type()
Prefer isinstance(x, cls): it accepts subclasses. type(x) is cls only matches the exact class.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.10 | classinfo can be a union type such as int | str. |
Related
issubclass()· Return True if a class is a subclass of another class (or of any class in a tuple or union). A class is a subclass of itself.type()· With one argument, return an object's type. With three arguments, create a new class dynamically.callable()· Return True if an object can be called like a function: functions, classes, methods and objects with __call__().- Python Data Types · tutorial
- Python Type Hints · tutorial