Skip to content

Python isinstance() Function Explained with Examples

Python isinstance() Function Explained with Examples Cover image

In this tutorial, you’ll learn how the Python isinstance function works and how it can be used in your Python programming. The Python isinstance() function allows you to check if an object belongs to a particular data type or class. Further, it lets you work with a selecting of different classes.

By the end of this tutorial, you’ll have learned:

  • How to use the Python isinstance function
  • How to check for native data types using the isinstance function
  • How to check for multiple types using the isinstance function
  • How to check for custom classes using the isinstance function
  • How to check for inherited classes using the isinstance function

Python isinstance Function

Before diving into examples, let’s take a look at the Python isinstance() function. The function takes only two parameters and returns a boolean value, True or False.

# The Syntax of the isinstance() Function
isinstance(
   object,        # The object to check
   classinfo      # The class, type or tuple of classes and types
)

Let’s take a look at these two parameters:

  • object= refers to the object to check, such as a variable of a value
  • classinfo= refers to the classes or types to check. The function expects either a single class or type, or a tuples of classes or types.

The function will return a boolean value if the object matches the type or class. If the classinfo= parameter isn’t a class, type, or tuple or classes or types, the function raises a TypeError.

Checking for Native Types Using Python isinstance

In this section, we’ll take a look at an example of how to use the isinstance() function to check if a value is a provided type. Let’s take a look at creating a list and checking its type using the isinstance() function.

# Checking for Native Types Using Python isinstance()
a_list = [1,2,3,4]
print(isinstance(a_list, list))

# Returns: True

We can see that when we tried to check whether the list was, in fact, a list that the function returned True. Let’s try this again, but this time see if the list is a tuple:

# Checking for Native Types Using Python isinstance()
a_list = [1,2,3,4]
print(isinstance(a_list, tuple))

# Returns: False

In the next section, you’ll learn how to use the Python isinstance function to check for multiple types.

Checking for Multiple Types Using Python isinstance

The Python isinstance() function has a special trick: it accepts multiple types or classes to check against. We can pass in a tuple of different types to check against. Let’s recreate our example from above but check against both tuple or list types.

This evaluates as an or expression, where the function returns a True if the type of the object matches any of the types provided.

# Check Against Multiple Types Using Python isinstance()
a_list = [1,2,3,4]
print(isinstance(a_list, (tuple, list)))

# Returns: True

This can be especially helpful when you’re returning data from somewhere and want to see how you can use that data. For example, you may want to check if a variable is a numeric data type that you can apply math operations on.

Checking for Custom Class Types Using Python isinstance

The Python isinstance function can be particularly helpful when working with classes. Just like checking the type of a variable, you can also check against different classes.

In this case, the function works in exactly the same way. Let’s take a look. We’ll create a new class, Person(), instantiate a new object, and then use the isinstance() function to check its class.

# Using the Python isinstance() Function to Check the Class
class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f'Hi! My name is {self.name}')

Nik = Person('Nik')

print(isinstance(Nik, Person))

# Returns: True

In the above example, we were able to confirm that class type of our new object.

Checking for Inherited Class Types Using Python isinstance

Let’s take our earlier example one step further and confirm that we can even use the function to check against inherited classes. This can be particularly helpful when you’re working with complex classes and need to ensure that objects are properly assigned to classes.

The function works in the same way but is able to confirm the inherited class. What’s great (and helpful) is that the function will also return True when checking against the parent class!

class Person:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f'Hi! My name is {self.name}')

class Employee(Person):
  def __init__(self, name):
    super().__init__(name)

Nik = Employee('Nik')

print(isinstance(Nik, Employee))
print(isinstance(Nik, Person))

# Returns: 
# True
# True

Sorting Items Into Different Lists Based on Python Types

One helpful implementation of the Python isinstance function is the ability to sort a different array of values into different lists. Say you have a list containing many different data types, you’re able to sort the items into different lists by using the isinstance() function.

Let’s take a look at how we can do this:

# Sorting values based on type
big_list = [1,"datagy", (1,2,3), ['apples', 'green'], 'data!', 3.14]

collections = []
numeric = []
strings = []
other = []

for item in big_list:
    if isinstance(item, (int, float)):
        numeric.append(item)
    elif isinstance(item, (tuple, list, dict, set)):
        collections.append(item)
    elif isinstance(item, str):
        strings.append(item)
    else:
        other.append(item)

print(f'{collections=}')
print(f'{numeric=}')
print(f'{strings=}')

# Returns:
# collections=[(1, 2, 3), ['apples', 'green']]
# numeric=[1, 3.14]
# strings=['datagy', 'data!']

Conclusion

In this tutorial, you learned how to use the Python isinstance function. You learned how the syntax of the function is constructed and what parameters it accepts. You then learned how to use the function to check for a single type and for multiple types. You then learned how to use the function with custom classes, as well as inherited classes. Finally, you learned a practical example of how to sort different items into different lists.

Additional Resources

To learn more about related topics, check out the tutorials below:

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *