isinstance allows you to check whether an object belongs to a certain class or subclass. This function basically answers the question, “does it belong to an instance or not?” where the subclasses can be either lists, dictionaries, strings etc.

How To Use isinstance() Function in Python

>>>isinstance(53, int)
True

Note that in the first argument, we check the object itself and in the second argument, we check if the object belongs to the certain class we have put in. The answer comes out to be true as 53 is indeed an integer.

How To Check If Variable Is A String In Python?


This is a simple enough format but of course, one has to obey the rules of syntax. For example, if we want to check if 53 is a string (denoted as ‘53’ in code if it is a part of string) and we write the following:

>>>isinstance(53, str)
False

The answer will come out to be false, but if we write the following:

>>>isinstance(‘53’, str)
True

The answer will come out to be true.

How To Check If Variable Is Instance Of Multiple Classes?

Another interesting use of this function is to use it as a tuple of instances. Basically, the question, “is the object an instance of float, integer, or string?” is answered when we write.

>>>isinstance(53, (float, int, str))
True

Here, the answer comes out to be true because 53 is indeed an integer. Now the above is condensed version of writing the following long and tedious code:

>>>isinstance(53, float) or isinstance(53, int) or isinstance(53, str)
True

Semantically, both are identical and will give the same result but the latter is unnecessarily long, and is harder to write than the former.

How does isinstance work with inheritance?

You can use isinstance to find if an object is from a class or that class has inherited from another class (parent class). For example check below:

class Parent():
    pass
class Child(Parent):
    pass
child = Child()
parent = Parent()
print(isinstance(child, Child)) #True
print(isinstance(child, Parent)) #True
print(isinstance(parent, Child)) #False

In short, an object will be an instance of a class it has inherited from.

If you would like to learn more Python check out this certificate course by Google: IT Automation with Python