Python’s isinstance()
function helps you determine if an object is an instance of a specified class or its superclass, aiding in writing cleaner and more robust code. You use it to confirm that function parameters are of the expected types, allowing you to handle type-related issues preemptively. This tutorial explores how isinstance()
works, its use with subclasses, and how it differs from type()
.
By the end of this tutorial, you’ll understand that:
isinstance()
checks if an object is a member of a class or superclass.type()
checks an object’s specific class, whileisinstance()
considers inheritance.isinstance()
correctly identifies instances of subclasses.- There’s an important difference between
isinstance()
andtype()
.
Exploring isinstance()
will deepen your understanding of the objects you work with and help you write more robust, error-free code.
To get the most out of this tutorial, it’s recommended that you have a basic understanding of object-oriented programming. More specifically, you should understand the concepts of classes, objects—also known as instances—and inheritance.
For this tutorial, you’ll mostly use the Python REPL and some Python files. You won’t need to install any libraries since everything you’ll need is part of core Python. All the code examples are provided in the downloadable materials, and you can access these by clicking the link below:
Get Your Code: Click here to download the free sample code that you’ll use to learn about isinstance() in Python.
It’s time to start this learning journey, where you’ll discover the nature of the objects you use in your code.
Why Would You Use the Python isinstance()
Function?
The isinstance()
function determines whether an object is an instance of a class. It also detects whether the object is an instance of a superclass. To use isinstance()
, you pass it two arguments:
- The instance you want to analyze
- The class you want to compare the instance against
These arguments must only be passed by position, not by keyword.
If the object you pass as the first argument is an instance of the class you pass as the second argument, then isinstance()
returns True
. Otherwise, it returns False
.
Note: You’ll commonly see the terms object and instance used interchangeably. This is perfectly correct, but remembering that an object is an instance of a class can help you see the relationship between the two more clearly.
When you first start learning Python, you’re told that objects are everywhere. Does this mean that every integer, string, list, or function you come across is an object? Yes, it does! In the code below, you’ll analyze some basic data types:
>>> shape = "sphere"
>>> number = 8
>>> isinstance(shape, str)
True
>>> isinstance(number, int)
True
>>> isinstance(number, float)
False
You create two variables, shape
and number
, which hold str
and int
objects, respectively. You then pass shape
and str
to the first call of isinstance()
to prove this. The isinstance()
function returns True
, showing that "sphere"
is indeed a string.
Next, you pass number
and int
to the second call to isinstance()
, which also returns True
. This tells you 8
is an integer. The third call returns False
because 8
isn’t a floating-point number.
Knowing the type of data you’re passing to a function is essential to prevent problems caused by invalid types. While it’s better to avoid passing incorrect data in the first place, using isinstance()
gives you a way to avert any undesirable consequences.
Take a look at the code below:
>>> def calculate_area(length, breadth):
... return length * breadth
>>> calculate_area(5, 3)
15
>>> calculate_area(5, "3")
'33333'
Your function takes two numeric values, multiplies them, and returns the answer. Your function works, but only if you pass it two numbers. If you pass it a number and a string, your code won’t crash, but it won’t do what you expect either.
The string gets replicated when you pass a string and an integer to the multiplication operator (*
). In this case, the "3"
gets replicated five times to form "33333"
, which probably isn’t the result you expected.
Things get worse when you pass in two strings:
>>> calculate_area("5", "3")
Traceback (most recent call last):
File "<python-input-8>", line 1, in <module>
calculate_area("5", "3")
~~~~~~~~~~~~~~^^^^^^^^^^
File "<python-input-5>", line 2, in calculate_area
return length * breadth
~~~~~~~^~~~~~~~~
TypeError: can't multiply sequence by non-int of type 'str'