Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a python c-extension method as a classmethod?

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?

like image 969
Dov Grobgeld Avatar asked Nov 12 '13 20:11

Dov Grobgeld


1 Answers

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

like image 168
alko Avatar answered Nov 14 '22 22:11

alko