Python Forum

Full Version: Adding C methods to a pure python class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.


Hi, I have a question on the C extension. Please guide me if it's not the right place.

I wanted to add C methods into a pure python class, but I couldn't find any documentation on that.
After hours of hacking the python source, I finally succeeded to do that.
I attached a POC code for Python 2.7.
Can anyone comment on whether this kind of hack - implementing only a part of a class in C,
instead of implementing the whole class in C - will be likely supported on future Python versions?


* python source

  class X(object):
    pass

  import x_ext
  X().test(1)

* C extension

  static PyObject *x_test(PyObject *self, PyObject *args)
  {
    puts("test");
    PyObject_Print(args, stdout, 0);
    puts("");
    Py_RETURN_NONE;
  }
  PyMODINIT_FUNC initx_ext(void)
  {
    Py_InitModule("x_ext", NULL);
    {
      PyObject *type = PyDict_GetItemString(PyEval_GetGlobals(), "X");
      static PyMethodDef test_def = {"test", (PyCFunction)x_test, METH_VARARGS, NULL};
      PyObject *descr = PyDescr_NewMethod((PyTypeObject *)type, &test_def);
      PyObject_SetAttrString(type, test_def.ml_name, descr);
      Py_DECREF(descr);
    }
  }
This definitely looks like a hack to me, lol.  Anytime there's side effects with importing a package, that smells like a hack.  I think it would be better to just define functions as part of the module, then attach them after importing.  Something like this:
import x_ext

class X:
    def __init__(self):
        self.test = x_ext.test

X().test(1)