PythonBuilt-in functions
isinstance()
Checks whether an object is of a given type, or of a subtype of it.
- Returns
TrueorFalse.
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
Truealso passes theisinstance(x, int)test. - Instead of checking the type, it is often better to just try the operation and handle the exception.
Related entries
#- type()Returns the type of an object.
- bool()Converts a value to True or False according to the rules of truthiness.
- int()Converts a value to an integer.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- InheritanceBuilding one class on top of another: the derived class inherits the base class’s methods and can extend or override them.
Spotted a mistake or missing an example? Write to us.