The Versatility of The 'isinstance' Method in Python
penncurtis
Posted on June 6, 2023
What & Why
Of all the methods that I have encountered so far in my time using Python, I found the 'isinstance' method to be the most useful, versatile, and reliable.
This method thrives in scenarios that involve many to many relationships, exchanges of information between files and classes, and even within methods themselves.
To put it as simply as possible, the 'isinstance' method is useful to check if an object or variable is of a specified data type or class type.
Structure & Syntax
The 'isinstance' method takes two arguments, both of which are mandatory for its functionality. The first argument is the name of the object/variable that we want to check. The second argument is the type of class that we want to cross-check the object/variable against. You can also check for multiple classes or types.
Execution and Examples
Using 'isinstance' we can check to see if a variable is a number or a string:
n = 100
result = isinstance(n, int)
if result:
print('Yes')
else:
print('No')
## output
Yes
As we can see in the example above, the isinstance method checks to see if the value of 'n' is indeed an integer. The boolean value that the method returns results in the output of 'Yes'. If we were to check to see if 'n' was a string we would get the opposite output.
n = 100
result = isinstance(n, str)
if result:
print('Yes')
else:
print('No')
## output
No
To check for multiple classes or types, we would simply include them in parenthesis as the second variable.
greeting = "hello world!"
result = isinstance(greeting, (int, float))
if result:
print('Yes')
else:
print('No')
## output
No
Obviously, since the greeting is not an integer or a float, the method returns False. We can also compare our variable/object to other python classes.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
emp = Employee("Emma", 100000)
## checking if emp is an Employee
print(isinstance(emp, Employee))
## output
True
Because our emp "Emma" met the criteria dictated by the Employee class, the method returns True.
Culmination & Conclusion
Understanding 'isinstance' is pivotal to successfully coding in python. Hopefully this blog post has helped resolve any outstanding queries the reader may have had with regards to this method. As one of the most powerful tools I have encountered so far in this coding language, I hope I did it justice in portraying its efficacy.
Posted on June 6, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.