_PyObject_New / PyObject_Init / PyInstance_New / etc?

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat May 19 16:15:11 EDT 2007


En Sat, 19 May 2007 10:54:32 -0300, Gre7g Luterman <hafeliel at yahoo.com>  
escribió:

> I'm so confuzzled! How do I instantiate my new C Python object from C?
> I tried inserting some code with _PyObject_New and PyObject_Init:
>
> Then I compiled, went into the Python interpreter and tried it.  I would
> have expected Noddy_name to create and destroy a Noddy object just like
> noddy2.Noddy() does from the interpreter, but it doesn't:

 From Python, you create a Noddy object by *calling* its type. Do the same  
in C:

return PyObject_CallObject((PyObject *) &NoddyType, NULL);

Or any other suitable variant of PyObject_CallXXX. (I've answered this  
same question yesterday, when I was not sure about this; then I've tried  
it and it appears to be working. But I've not read any docs telling this  
is *the* right way to create an object).

> I've tried this as above, and with PyInstance_New, with PyObject_New (no
> underscore), and PyObject_Call, but none of them work as I would expect.  
> So
> what is the *CORRECT* way to do this?  Obviously I'm neglecting something
> important.

PyInstance_New is for old style classes. PyObject_New only initializes the  
object structure, and this is enough for most builtin types that usually  
don't define __init__ (or tp_init). You were right with PyObject_Call, but  
maybe you didn't invoke it correctly.

-- 
Gabriel Genellina




More information about the Python-list mailing list