Question

I'm writing a python wrapper for a C++ class that provide several static methods for alternate "constructors". I'm wondering how to export these through the python c-api?

Here is a stub of the relevant C++ code.

 PyObject *PyFoo_FromFoo(Foo foo);

 // This should be a class method that create a new instance of PyFoo().
 PyObject *
 PyFoo_Gen1(PyObject *self, PyObject *args)
 {
     Foo foo;  // Init this according to args

     return PyFoo_FromFoo(foo);
 }

 static PyMethodDef PyFoo_methods[] = {
    {"Gen1", (PyCFunction)PyFoo_Gen1, METH_VARARGS, "Gen1 foo creator" },
    {NULL}  /* Sentinel */
 };

 PyTypeObject PyFooType = {
   :
   PyFoo_methods, /* tp_methods */
   :
 }

 PyObject *PyFoo_FromFoo(Foo foo)
 {
    PyFoo *v = (PyFoo*)PyObject_New(PyFoo, &PyFooType);
    v->foo = foo;
    return (PyObject*)v;
 }

What would be the corresponding of using the classmethod() function (directly or through the @classmethod decorator) for Gen1() in the example above?

Was it helpful?

Solution

Starting from python 2.3 it can be done using METH_CLASS. See datetime module for a sample.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top