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:

Python
>>> isinstance(42, int)
True

isinstance() Signature

Python Syntax
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 the object is an instance of classinfo or a subclass thereof.
  • Returns False if the object is not an instance of classinfo.

isinstance() Examples

With a number and class as arguments:

Python
>>> isinstance(3.14, float)
True
>>> isinstance(3.14, int)
False

With a number and a tuple of classes as arguments:

Python
>>> isinstance(42, (int, float))
True

With a union type as an argument:

Python
>>> 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:

Python
>>> 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader