Is 'x' an instance of a new-style class?

MatthewS schaefer.mp at gmail.com
Tue Sep 16 14:53:32 CEST 2008


On Sep 16, 11:38 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Tue, 16 Sep 2008 05:26:14 -0300, MatthewS <schaefer... at gmail.com>  
> escribió:
>
> > I've seen the question raised several times here, but apparently never
> > answered. Since PyInstance_Check returns False for new-style class
> > instances, is there a standard procedure for testing this using the C-
> > Api?
>
> > I would greatly appreciate some help with this.
>
> In Python you would write isinstance(x, object). In C, "object" is  
> PyBaseObject_Type, and a direct translation would be  
> PyObject_IsInstance(x, PyBaseObject_Type), or perhaps  
> PyObject_TypeCheck(x,  &PyBaseObject_Type) (to mimic how other PyXXX_Check  
> are implemented, and probably faster)
>
> --
> Gabriel Genellina

Thanks Gabriel, the second solution seems to work based on my tests.
So I have this now this test:

static BOOL IsPythonInstance( PyObject * src )
{
	{
		// old style classes or instances or new style classes or instances
		if( ( PyInstance_Check( src ) ) || ( PyClass_Check( src ) ) ||
PyObject_TypeCheck( src, &PyBaseObject_Type) )
		{
			return TRUE;
		}

		return FALSE;
	}
}




More information about the Python-list mailing list