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,350 points
25 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
• 56,520 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 ariaholic
• 7,340 points
41 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 in Python by Mohammad
• 3,060 points
24 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 in Python by Mohammad
• 3,060 points
19 views
0 votes
1 answer

What is the difference between list and tuple?

Lists are mutable(values can be changed) whereas ...READ MORE

answered May 4, 2018 in Python by aayushi
• 750 points
1,564 views
+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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 216 views
+4 votes
6 answers
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
• 56,520 points
330 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
• 56,520 points
652 views