"isinstance" question

John Nagle nagle at animats.com
Tue Jun 22 22:45:07 EDT 2010


   I want to test whether an object is an instance of any user-defined
class.  "isinstance" is less helpful than one would expect.

 >>> import types
 >>> class foo() : # define dummy class
...     pass
...
 >>> x = foo()
 >>>
 >>> type(x)
<type 'instance'>
 >>>
 >>> isinstance(x, types.ClassType)
False
 >>> isinstance(x, types.InstanceType)
True
 >>> foo
<class __main__.foo at 0x004A2BD0>
 >>> x
<__main__.foo instance at 0x020080A8>

So far, so good. x is an InstanceType.  But let's try a
class with a constructor:

 >>> class bar(object) :
...    def __init__(self, val) :
...      self.val = val
...
 >>> b = bar(100)
 >>> b
<__main__.bar object at 0x01FF50D0>
 >>> isinstance(b, types.InstanceType)
False
 >>> isinstance(b, types.ClassType)
False
 >>>>>> bar
<class '__main__.bar'>

Without a constructor, we get an "instance".  With a constructor,
we get an "object", one which is not an InstanceType.

One might think that testing for types.ObjectType would help.  But
no, everything is an ObjectType:

 >>> isinstance(1, types.ObjectType)
True
 >>> isinstance(None, types.ObjectType)
True

So that's useless.

I have to be missing something obvious here.

(CPython 2.6)

				John Nagle



More information about the Python-list mailing list