[Tutor] isinstance versus 'is'?
Alan Gauld
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
> odd.
>
>>>> a = 5
>>>> isinstance(a, int)
> True
>>>> a is int
> False
>
> What happened there? Don't these do the same thing?
Evidently not!
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:
>>> isinstance(5,int)
True
>>> int
<type 'int'>
>>> 5
5
What you may be getting confused with is:
>>> type(5) is int
True
>>>
But even then this is not identical to isinstance,
because the latter checks for subclass relationships
too:
>>> class C: pass
...
>>> class D(C): pass
...
>>> c = C()
>>> d = D()
>>> isinstance(c, C)
True
>>> isinstance(c, D)
False
>>> isinstance(d, C)
True
>>> isinstance(d, D)
True
>>> type(c) is C
True
>>> type(d) is type(C)
False
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.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list