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 is 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
True
if theobject
is an instance ofclassinfo
or a subclass thereof. - Returns
False
if theobject
is not 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, raising a TypeError
otherwise.
Related Resources
Tutorial
Object-Oriented Programming (OOP) in Python
In this tutorial, you'll learn all about object-oriented programming (OOP) in Python. You'll learn the basics of the OOP paradigm and cover concepts like classes and inheritance. You'll also see how to instantiate an object from a class.
For additional information on related topics, take a look at the following resources:
- 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)
- Python Type Checking (Course)
- Python Type Checking (Quiz)