create a class instance from C API?

Carl Banks pavlovevidence at gmail.com
Mon Sep 28 12:13:25 EDT 2009


On Sep 28, 8:19 am, "lallous" <lall... at lgwm.org> wrote:
> 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



More information about the Python-list mailing list