How To Use type() And isinstance() In Python

How To Use type() And isinstance() In Python

When writing a program in Python, you may need to check what type or class a given object is. You may also want to see if a particular object is an instance of a particular class. There are two built-in functions for doing this type of thing in Python. These are the type() function, and the isinstance() function. Everything in Python is an object, and the type() function will tell you what type of object a given variable is. Let’s look at a few examples of type() and isinstance() in Python now.


Two Different Classes

The code above simply defines two classes. We can see there is a Monitor class and a Keyboard class. Pretty simple.


Create Objects Of The Classes

This code here build on what we learned in the object-oriented Python tutorial. We are instantiating four distinct objects.


Using type() To Inspect The Object Type

<class '__main__.Monitor'>
<class '__main__.Keyboard'>

Here we use the type() function in combination with the print() function to print out to the console what type an object is. We see the familiar Python notation that is used to display a class type. This is the expected result. We have one object with a type of Monitor and another with a type of Keyboard.

Comparing Two Types Together

True
False

The type() function is useful because you can use it to compare two different objects to see if they are the same type. The code above shows that the two Monitor objects are of the same type, whereas the Monitor and the Keyboard are obviously different types.


Use isinstance() To Compare A Specific Instance To A Known Type

True
True
False

To see if a given object is an instance of a particular class, you can use the isinstance() function as seen just above. When using isinstance(), the first argument passed is the object you want to check. The second argument passed is the Object Type you are comparing against. In other words, is this first argument an instance of this second argument. When the code runs we get results we would expect. monitor1 is an instance of the Monitor class. keyboard1 is an instance of the Keyboard class. However keyboard2 is not an instance of the Monitor class.


Everything Is An Object

In Python, everything is a subclass of the Object class. We can test this out with our new skills using the isinstance() function. In the code below we check various objects such as a string, a boolean, a number, a class, and even a lambda function against Python’s built-in Object base class. As we can see, every single one of the tests comes back True! So you see, everything really is an object in Python.

True
True
True
True
True
True
True