What Does isinstance() Do in Python?

What Does isinstance() Do in Python?

by Ian Eyre 0 Comments intermediate python

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, while isinstance() considers inheritance.
  • isinstance() correctly identifies instances of subclasses.
  • There’s an important difference between isinstance() and type().

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:

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:

  1. The instance you want to analyze
  2. 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.

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:

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

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

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

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

Locked learning resources

The full article is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Article

Already a member? Sign-In

About Ian Eyre

Ian is an avid Pythonista and Real Python contributor who loves to learn and teach others.

» More about Ian

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

What Do You Think?

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!

Become a Member to join the conversation.

Keep Learning

Related Topics: intermediate python