isinstance()

Checks whether an object is of a given type, or of a subtype of it.

Returns
True or False.
On this page

Example

#
Python
def describe(value):
    if isinstance(value, bool):
        return "boolean"
    if isinstance(value, (int, float)):
        return "number"
    if isinstance(value, str):
        return "text"
    return "something else"

for item in [7, 2.5, "HTML", True, None]:
    print(describe(item))
Resultsaved result, you can check it
number
number
text
boolean
something else

Definition and usage

#

The isinstance(object, type) function returns True if the object is an instance of the given type, or of a class that inherits from it. It's the recommended way to check types inside conditions.

As the second argument you can pass a tuple of types: isinstance(x, (int, float)) checks whether the value is any of those number types. Since Python 3.10 you can also write it as a union: int | float.

Remember that bool inherits from int, so isinstance(True, int) returns True. If you want to exclude boolean values, check for them separately.

Syntax

#
Syntax
isinstance(object, classinfo)

Parameters

#
  • object

    any value

    The object being checked.
  • classinfo

    a type, a tuple of types, or a union

    The type, or several types, to check against.

Good practices

#
  • Check boolean values before numbers, because True also passes the isinstance(x, int) test.
  • Instead of checking the type, it is often better to just try the operation and handle the exception.

Related entries

#

Spotted a mistake or missing an example? Write to us.