create a class instance from C API?

L

lallous

Hello

How to programmatically create a class instance of a given Python class?

For example to create a new list there is the PyObject *PyList_New() but
suppose the user already defined a class:

class X: pass

How to create an instance of it from my C extension module?

Regards,
Elias
 
C

Carl Banks

Hello

How to programmatically create a class instance of a given Python class?

For example to create a new list there is the PyObject *PyList_New() but
suppose the user already defined a class:

class X: pass

How to create an instance of it from my C extension module?

Same way you'd do it in Python: call it. Use PyObject_Call or any of
it's convenient variants. Example (leaving off all the error-checking
stuff):

mod = PyImport_ImportModule(modname);
cls = PyObject_GetAttrStr(mod,classname);
inst = PyObject_CallFunctionObjArgs(cls,NULL);


Carl Banks
 
L

lallous

Thanks Carl, that does it!

--
Elias

Carl Banks said:
Same way you'd do it in Python: call it. Use PyObject_Call or any of
it's convenient variants. Example (leaving off all the error-checking
stuff):

mod = PyImport_ImportModule(modname);
cls = PyObject_GetAttrStr(mod,classname);
inst = PyObject_CallFunctionObjArgs(cls,NULL);


Carl Banks
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,836
Messages
2,569,750
Members
45,545
Latest member
rapter____0

Latest Threads

Top