The built-in isinstance()
function checks if an object is an instance of a specified class or a subclass thereof, returning a Boolean value. It’s a versatile tool for explicit type checking in Python, as it considers subclass relationships:
>>> isinstance(42, int)
True
Copied! isinstance()
Signature
isinstance(object, classinfo)
Copied! Arguments Argument Description object
The object to check. classinfo
A class, tuple of classes, or union type to check against. Return Value
True
if the object
is an instance of classinfo
or a subclass thereof.False
if the object
isn’t an instance of classinfo
.isinstance()
Examples
With a number and class as arguments:
>>> isinstance(3.14, float)
True
>>> isinstance(3.14, int)
False
Copied!
With a number and a tuple of classes as arguments:
>>> isinstance(42, (int, float))
True
Copied!
With a union type as an argument:
>>> isinstance(42.0, int | float)
True
Copied! isinstance()
Common Use Cases
The most common use cases for the isinstance()
function include:
isinstance()
Real-World Example
Say you’re implementing a function that processes different types of numerical data. You can use isinstance()
to ensure the input is of a valid type:
>>> def process_number(number):
... if isinstance(number, (int, float)):
... return number ** 2
... else:
... raise TypeError("the input must be an int or float")
>>> process_number(4)
16
>>> process_number(4.5)
20.25
>>> process_number("4")
Traceback (most recent call last):
...
TypeError: the input must be an int or float
Copied!
In this example, isinstance()
ensures that the function processes only integers and floats, and raises a TypeError
otherwise.
For additional information on related topics, take a look at the following resources:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4