C API: how to tell if x is a new style instance?

Mike C. Fletcher mcfletch at rogers.com
Thu Jan 29 11:18:21 CET 2004


Michal Vitecek wrote:

>Mike C. Fletcher wrote:
>  
>
>>Well, I don't actually know how to check for the spiritual state of a 
>>new-style class, but here's how to tell if an instance is an instance of 
>>a new-style class:
>>
>>  * Note that a new-style class is a sub-class of type, while
>>    old-style classes are not
>>    
>>
Ignore this, it's wrong.  Should have read: Note that a new-style class 
is an *instance* of a sub-class of type, while old-style classes are not.

>>  * Check if isinstance( instance.__class__, type )
>>    
>>
If the above had been true this would have read issubclass( ... ), trust 
the code more than the descriptions :) .

>>  * <Insert mystical spiritual damnedness check here>
>>    
>>
>
> ahh - it helped. thank you!
> 
> but, so it means that PyType_Check() doesn't work for new style
> classes' instances? it returns 0 but i understood from the
> documentation that it should return 1:
>  
>
Nope, I'm just an idiot :) .  The code was saying what I intended, but 
not the text.  The docs you're reading are saying "if it's an instance 
of the meta-class type, or a sub-class of the meta-class type"... to 
illustrate:

 >>> class r( type ):
...     pass
...
 >>> class s:
...     __metaclass__ = r
...    
 >>> s
<class '__main__.s'>
 >>> s.__class__
<class '__main__.r'>
 >>> isinstance( s, type )
1
 >>> isinstance( s(), type )
0

You wouldn't want instances of s claiming to be types.  But instances of 
r, (which is a sub-class of type), should claim to be types (s is an 
instance of r).

Hope that resolves any confusion,
Mike

> """
> int PyType_Check(PyObject *o)
>     Returns true if the object o is a type object, including instances
>     of types derived from the standard type object. Returns false in
>     all other cases.
> """
>  
>
_______________________________________
  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://members.rogers.com/mcfletch/






More information about the Python-list mailing list