Input validation
Validate an input before applying type-specific operations.
Python · Function
Tests whether an object is an instance of a type, accepted subclass, tuple of types, or Union Type. It returns a Boolean and supports subclass-aware checks.
isinstance() tests whether an object belongs to a specified type, any type in a tuple, or a type related through direct, indirect, or virtual subclassing. It returns a Boolean result; an invalid classinfo argument raises TypeError, subject to earlier successful checks.
isinstance(object, classinfo, /)| Name | Type | Description |
|---|---|---|
object | object | The value whose instance or subclass relationship is tested. |
classinfo | type | tuple[type, ...] | union type | A type, recursively nested tuple of types, or a Union Type of multiple types. |
True if object is an instance of classinfo or one of its accepted subclasses; otherwise False.
value = 42
if isinstance(value, int):
print("integer")
if isinstance(value, (str, float)):
print("text or decimal")The first test succeeds because 42 is an int. The second test checks several acceptable types and therefore does not print anything.
Validate an input before applying type-specific operations.
Accept several alternative representations in one conditional.
Recognize derived or virtual implementations through a base type.
isinstance(value, Type) returns True when value is an instance of Type or of a direct, indirect, or virtual subclass. Otherwise it returns False.
Follow-up: How can one test several types? Pass a tuple of type objects, such as isinstance(value, (int, float)); the result is true if any candidate matches.
The second argument may be a type, a recursively nested tuple of type objects, or a union type. For a tuple, the function succeeds when the object matches at least one contained type.
Follow-up: What happens if classinfo is invalid? A TypeError is raised, although an earlier successful tuple check can prevent that error.
isinstance() accounts for subclass relationships, including direct, indirect, and virtual subclasses. This makes it suitable when accepted derived types should pass a type check.
Follow-up: When was union-type support added? The documentation records that classinfo can be a Union Type starting in Python 3.10.
issubclasstypeUnion Type