isinstance()
    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
isinstance() Signature
isinstance(object, classinfo)
Arguments
| Argument | Description | 
|---|---|
object | 
The object to check. | 
classinfo | 
A class, tuple of classes, or union type to check against. | 
Return Value
- Returns 
Trueif theobjectis an instance ofclassinfoor a subclass thereof. - Returns 
Falseif theobjectisn’t an instance ofclassinfo. 
isinstance() Examples
With a number and class as arguments:
>>> isinstance(3.14, float)
True
>>> isinstance(3.14, int)
False
With a number and a tuple of classes as arguments:
>>> isinstance(42, (int, float))
True
With a union type as an argument:
>>> isinstance(42.0, int | float)
True
isinstance() Common Use Cases
The most common use cases for the isinstance() function include:
- Explicitly checking data types in conditional statements
 - Ensuring input data conforms to expected data types
 - Validating arguments in functions and methods
 
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
In this example, isinstance() ensures that the function processes only integers and floats, and raises a TypeError otherwise.
Related Resources
Tutorial
What Does isinstance() Do in Python?
Learn what isinstance() does in Python and how to use this built-in function to check an object's type. Discover its practical uses along with key limitations.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
 - Basic Data Types in Python: A Quick Exploration (Tutorial)
 - Duck Typing in Python: Writing Flexible and Decoupled Code (Tutorial)
 - Python Type Checking (Guide) (Tutorial)
 - Intro to Object-Oriented Programming (OOP) in Python (Course)
 - Object-Oriented Programming (OOP) in Python (Quiz)
 - Exploring Basic Data Types in Python (Course)
 - Basic Data Types in Python: A Quick Exploration (Quiz)
 - Getting to Know Duck Typing in Python (Course)
 - Python Type Checking (Course)
 - Python Type Checking (Quiz)