Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (83 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

What Is Isinstance In Python And How To Implement It?

Published on Sep 30,2019 13.1K Views

41 / 62 Blog from Python Fundamentals

Python is one of the most powerful programming languages available in the market today. Python also supports implementation of other programming languages within its ecosystem like Java, C as well as C++. Out of the many modules and functions that are available in Python ecosystem, one such that stands out among the rest is the isinstance in Python. Thus in this article we will speak in detail about the isinstance, its uses and the features it brings to the table.

Following pointers will be covered in this article,

Let’s Begin!

What is Isinstance in Python?

The Python isinstance is used to check if the first object that is the argument is an instance or subclass of the classinfo class that is the second argument. 

The syntax for the isinstance in Python is as follows. 

isinstance(object, classinfo)

 

Let us see what parameters and return value does Isinstance in Python have,

Parameter and Return Value of Isinstance

Parameter

Now that you are aware of the syntax for isinstance, let us take a closer look at the parametre it takes into account. 

  1. Object: This is the object that needs to be checked. 
  2. Classinfo: This the class, info or the tuple of classes that the object needs to be checked against. 

Return Value

When the isinstance is used in a program, the return value depends on a number of conditions, as explained in the pointers below. 

  1. True is returned if the object is a subclass of the classinfo or tuple of classes. 
  2. False is returned if the object is not a subclass of the classinfo or tuple of classes. 

If in a particular situation, the classinfo is not a type or a tuple of types, then a typeerror exception is raised onto the screen of the user. 

Examples 

To understand the use of isinstance  better, let us take a look at a few examples. 

Example #1

class Foo:
  a = 5
fooInstance = Foo()
print(isinstance(fooInstance, Foo))
print(isinstance(fooInstance, (list, tuple)))
print(isinstance(fooInstance, (list, tuple, Foo)))

Output

True

False

True

Isinstance In Python: Example #2

numbers = [1, 2, 3]
result = isinstance(numbers, list)
print(numbers,'instance of list?', result)
result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)
result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)
number = 5
result = isinstance(number, list)
print(number,'instance of list?', result)
result = isinstance(number, int)
print(number,'instance of int?', result)

Output

[1, 2, 3] instance of list? True

[1, 2, 3] instance of dict? False

[1, 2, 3] instance of dict or list? True

5 instance of list? False

5 instance of int? True

Example #3

# Python code for isinstance()
class Test:
a = 5
TestInstance = Test()
print(isinstance(TestInstance, Test))
print(isinstance(TestInstance, (list, tuple)))
print(isinstance(TestInstance, (list, tuple, Test))) 

Output

True

False

True

Let us continue with ‘Isinstance In Python’ article and and understand the use of Type method,

The use of Type in Python

Similar to the isinstance, there is another in built-in method in Python which is used to check the type pf variable that is being used during runtime. If a single argument or object is passed through the type method, it returns the type of the object that is being used during runtime. 

To understand this better, take a look at the example below. 

Isinstance In Python: Example #1.1

# Python code type() with a single object parameter
x = 5
s = "sampleoutput"
y = [1,2,3]
print(type(x))
print(type(s))
print(type(y)) 

Output 

class ‘int’

class ‘str’

class ‘list’

Example #1.2

# Python code for type() with a name,
# bases and dict parameter
o1 = type('X', (object,), dict(a='Foo', b=12))
print(type(o1))
print(vars(o1))
class test:
a = 'Foo'
b = 12
o2 = type('Y', (test,), dict(a='Foo', b=12))
print(type(o2))
print(vars(o2)) 

Output

{‘b’: 12, ‘a’: ‘Foo’, ‘__dict__’: , ‘__doc__’: None, ‘__weakref__’: }

{‘b’: 12, ‘a’: ‘Foo’, ‘__doc__’: None}

Let us compare Type and Isinstance in Python,

Difference between Type() and Isinstance

Type and isinstance in Python serve two very different functions. Take a look at the pointers below to understand the difference between them better. 

  1. If you need to check if an object has a certain type then it is best to use the isinstance. This is because the isinstance will be able to check if the object passed in the first argument is of the same type as that passed in the second argument. 
  2. On the other hand, the use of type is more preferred when you need to simply check the type of a particular object and not compare it against another. 

Example 

#Python code to illustrate duck typing
class User(object):
def __init__(self, firstname):
self.firstname = firstname
@property
def name(self):
return self.firstname
class Animal(object):
pass
class Fox(Animal):
name = "Fox"
class Bear(Animal):
name = "Bear"
# Use the .name attribute (or property) regardless of the type
for a in [User("SampleOutput"), Fox(), Bear()]:
print(a.name) 

Output 

SampleOutput 

Fox

Bear

Another reason not to use the type method is the lack of inheritance. Take a look at the examples shared below to understand this better. 

#python code to illustrate the lack of
#support for inheritance in type()
class MyDict(dict):
"""A normal dict, that is always created with an "initial" key"""
def __init__(self):
self["initial"] = "some data"
d = MyDict()
print(type(d) == dict)
print(type(d) == MyDict)
d = dict()
print(type(d) == dict)
print(type(d) == MyDict) 

Output 

False

True

True

False

So this it guys, this brings us to the end of this article. I hope you have understood Isinstance in Python and what it does.

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Got a question for us? Mention them in the comments section of this article and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 23rd March,2024

23rd March

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 20th April,2024

20th April

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

What Is Isinstance In Python And How To Implement It?

edureka.co