What are the differences between type and is instance

0 votes
What are the differences between these two code fragments? Using type():

import types

if type(a) is types.DictType:

do_something()

if type(b) in types.StringTypes:

do_something_else()

Using isinstance():

if isinstance(a, dict):

do_something()

if isinstance(b, str) or isinstance(b, unicode):

do_something_else()
Aug 6, 2018 in Python by bug_seeker
• 15,510 points
634 views

1 answer to this question.

0 votes

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance is less bad than checking identity of types because it seamlessly supports inheritance.

It's not that isinstance is good, mind you—it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).

basestring is, however, quite a special case—a builtin type that exists only to let you use isinstance (both str and unicode subclass basestring). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and basestring plus isinstance helps you do that—the overall structure of this idiom is something like:

if isinstance(x, basestring)

   return treatasscalar(x)

Try:

   return treatasiter(iter(x))

   except TypeError:

   return treatasscalar(x)

You could say that basestring is an Abstract Base Class ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with isinstance. The concept is obviously a growing one in Python, since PEP 3119, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.

The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that. ABCs as implemented in recent Python versions do however offer extra goodies: isinstance (and issubclass) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications for more on the TM DP, in general and specifically in Python, independent of ABCs).

answered Aug 6, 2018 by Priyaj
• 58,020 points

Related Questions In Python

0 votes
1 answer

What are the differences between type() and isinstance()?

To summarize the contents of other (already ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,460 points
681 views
0 votes
1 answer

What are the key differences between python and java?

There are a lot of pressing  topics ...READ MORE

answered Aug 2, 2019 in Python by Mohammad
• 3,230 points
687 views
0 votes
1 answer

What are the key differences between python 2 and python 3?

The key differences include changes in the ...READ MORE

answered Aug 14, 2019 in Python by Mohammad
• 3,230 points
1,062 views
0 votes
0 answers

What are the differences between numpy arrays and matrices? Which one should I use?

What are each's advantages and drawbacks? I've noticed ...READ MORE

Aug 8, 2022 in Python by krishna
• 2,820 points
614 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,069 views
0 votes
1 answer

What is the difference between Python and IPython?

There are few differences between Python and ...READ MORE

answered Jul 26, 2018 in Python by Priyaj
• 58,020 points
4,005 views
0 votes
1 answer

What is the difference between re.search and re.match?

The theoritical approach can be this way, re.match is ...READ MORE

answered Aug 10, 2018 in Python by Priyaj
• 58,020 points
11,922 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP