-1

I was looking at some code on the web, and I saw some code I'm not used to. The one that most called my attention was:

if not isinstance(string, str):
    #dosomething

What would be the difference if I did instead:

if type(string)!=str:
    #dosomething
dccsillag
  • 919
  • 4
  • 14
  • 25
  • General suggestion: when you have a python question use the python tag. If the question is specific to python-3.x use both tags. That should increase the number of viewers. – Scott May 15 '15 at 03:51

1 Answers1

3

First check out all the great answers here.

type() simply returns the type of an object. Whereas, isinstance():

Returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.

Example:

class MyString(str):
    pass

my_str = MyString()
if type(my_str) == 'str':
    print 'I hope this prints'
else:
    print 'cannot check subclasses'
if isinstance(my_str, str):
    print 'definitely prints'

Prints:

cannot check subclasses
definitely prints
Community
  • 1
  • 1
Scott
  • 6,089
  • 4
  • 34
  • 51