What is isinstance function in Python?

This is a very important fn in Python programming. It returns a Boolean stating whether the object is an instance or subclass of another object. In this post, I am going to explain about Python function “isinstance” and its different examples.

Python is a good and simple language for SysAdmins automation tasks. Bookmark the Index page and read more about Python.

Syntax

isinstance (object, classinfo)

Object : Required field**. This should be an object instance. Example: Any variable name you defined like int, mynum etc

Classinfo : This field is also required**. A class, type or a tuple containing classes, types or other tuples. Example: int, float, unicode, str, basestring etc..

You will get clarification after checking the practical examples listed below.

The code returns “True” if classinfo is a type object and object is an object of that type or of a subclass thereof. If object is not a class instance or an object of the given type, the function always returns False.

If classinfo is not a type or tuple of types, a TypeError exception is raised.

Examples:

Please go through the tutorial on Python variables before stating the exercise in isinstance section. You can check it from here >> Variables and Types – Python

isinstance('food', int)
False

isinstance('food', str)
True

isinstance('food', basestring)
True

Checking any of them!!

isinstance('food', (str, basestring, int))
True

isinstance('food', (str, basestring))
True

isinstance('food', (int, bool))
False

Example with if condition

teststring = "Tom"
if (teststring, basestring):
    print teststring
   ....:
Tom
teststring = "Tom"
if (teststring, basestring) and teststring == 'Tom':
    print teststring
   ....:
Tom
testfloat = 15.99
if isinstance(testfloat, float):
   ....:     print testfloat
   ....:
15.99
if isinstance(testfloat, float) and testfloat==15.99:
    print testfloat
   ....:
15.99

if isinstance(testfloat, float) and testfloat==15.98:
    print testfloat
   ....:
##No value

Why isinstance is more accurate than type?

The Python function function “type” is also doing the same thing, but less accurate. The examples below will explain it:

mystring = "Food"

type(mystring)
: str

type(mystring) == str
: True

type(mystring) == int
: False

Considering the example of defining a class, you can see isinstance is more accurate than type function.

: class mystring(str):
   ....:     pass
   ....:
: test = mystring()
: type(test)
: __main__.mystring

: type(test) == str
: False

 

I believe you have got some basic idea on Python isinstance function.
Let me know if you have any questions.

Arunlal Ashok

Sr. Linux Server Administrator. I'm managing Linux servers since 2012. I started this blog to share and discuss my ideas. Check My Profile in uPwork (oDesk) and create a job, if you need any administration help. Thanks!!

You may also like...

Leave a Reply

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