[Tutor] isinstance versus 'is'?
alan.gauld at yahoo.co.uk
Tue Jul 5 19:22:48 EDT 2016
On 05/07/16 20:05, Alex Hall wrote:
> I was double checking that I remembered the isinstance order of arguments
> correctly by using the command line interpreter, and found something very
>>>> a = 5
>>>> isinstance(a, int)
>>>> a is int
> What happened there? Don't these do the same thing?
Think about it. isinstance() is asking if a is an
instance of int. int is a type. 5 is an instance of
that type but it's not the type itself.
a is int
is asking if a and int are the same things
(are they actually the same object).
Clearly 5 is not the type int. We can check
this in the interpreter:
What you may be getting confused with is:
>>> type(5) is int
But even then this is not identical to isinstance,
because the latter checks for subclass relationships
>>> class C: pass
>>> class D(C): pass
>>> c = C()
>>> d = D()
>>> isinstance(c, C)
>>> isinstance(c, D)
>>> isinstance(d, C)
>>> isinstance(d, D)
>>> type(c) is C
>>> type(d) is type(C)
And to further complicate matters the above works
differently in v2 from v3(above)
The bottom line is that isinstance() is usually
the best choice.
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:
More information about the Tutor