isinstance is broken
Michael Hudson
mwh at python.net
Sat Jan 18 13:20:28 EST 2003
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.
> There is issubclass for that job:
>
> >>> issubclass(int,object)
> 1
Asking a different question.
[object]
/ \
(subclass)/ \(subclass)
/ \
/ \
[int]=======[type]
(instance)
> 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.
> Moreover, on a related note:
>
> >>> import re
> >>> reobj=re.compile('x')
> >>> isinstance(reobj,object)
> 1
> >>> reobj.__new__
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> AttributeError: __new__
>
> but regular expression objects are *not* instances of object (this is
> also documented).
This is more or less the same as before.
> I wonder if there is a plan to make regular expression
> objects regular objects in the near future
Not aware of any.
> For the moment, of course I can use
>
> class RE(object):
> def __init__(self,regexp):
> reobj=re.compile(regexp)
> for attr in dir(reobj):
> setattr(self,attr,getattr(reobj,attr))
>
> REobj=RE('x')
> REobj.__new__
> <built-in method __new__ of type object at 0x80e6280>
>
> Should I interpret the fact that isinstance(something,object) always returns
> true as a bug or is it intentional ?
Unavoidable would be my word.
Cheers,
M.
--
ARTHUR: Yes. It was on display in the bottom of a locked filing
cabinet stuck in a disused lavatory with a sign on the door
saying "Beware of the Leopard".
-- The Hitch-Hikers Guide to the Galaxy, Episode 1
More information about the Python-list
mailing list