isinstance is broken

Michele Simionato mis6 at pitt.edu
Sun Jan 19 00:42:24 CET 2003


Michael Hudson <mwh at python.net> wrote in message news:<7h3n0lyl3pf.fsf at pc150.maths.bris.ac.uk>...
> mis6 at pitt.edu (Michele Simionato) writes:
> 
> > There are inconsistencies in "isinstance".
> > 
> > Example 1:
> > 
> > >>> isinstance(int,object)
> > 1
> > 
> > gives no error message. I don't like it, an error should be
> > raised.
> 
> Heck, no.  'int' is an instance of 'type'; 'type' is a subclass of
> object.

I feel stupid not having thought of that :-(

> Example 2 
> > 
> > >>> class C: pass #does *not* inherit from object
> > >>> c=C() 
> > >>> isinstance(c,object) #???
> > 1
> > 
> > It is clear that c is *not* an instance of class object: 
> 
> Yes it is: c is of type instance; instance is a subtype of object.
> 
> ->> type(c)
> <type 'instance'>
> ->> type(c).__bases__
> (<type 'object'>,)
> 
> Here type(c) != c.__class__, one of the awkwardnesses that the
> type/class unification removes.
> 
> > for example it doesn't have the __new__ attribute:
> > 
> > >>> c.__new__
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in ?
> > AttributeError: C instance has no attribute '__new__'
> 
> However:
> 
> ->> type(c).__new__
> <built-in method __new__ of type object at 0x80f2380>
> 
> Objects/classobject.c:instance_getattr looks in c.__class__.
> 
> This function isn't much use, it seems.

Here I don't feel stupid; I didn't know that. You are saying essentially
that c *does* inherit __new__ from object, but it cannot be accessed with
c.__new__ due to an implementation detail (i.e. getattr looks for __class__
which is not there); it can be accessed via type(c) anyway.
This is an inconsistency of old style classes: they inherits from object
but you cannot access object methods in the usual way.

Thanks to everybody for the explanations,

                           Michele




More information about the Python-list mailing list