-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
1
  • 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. Commented May 15, 2015 at 3:51

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Feel free to comment on why you would downvote.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.