neodelphi
neodelphi

Reputation: 2786

Setting different doc string for functions of the same custom type defined with Python-C-API

I'm embedding python in a C++ application and wrote a function wrapper (like boost::python does). To achieve this, I created a custom python type and defined its PyTypeObject structure and set a tp_call function pointer.

This works fine, but now I would like to be able to set the documentation of the wrapped functions. For the moment, when I run help(some_function) in the Python interpreter, a generic documentation is printed. Setting tp_doc of the PyTypeObject structure doesn't help since it provides the same help string for all the wrapped functions.

I also tried to call

PyObject_SetAttrString((PyObject*)a_wrapped_function, "__doc__", PyUnicode_FromString("some doc"))

but this call returns -1, which means failure (this attribute is probably considered read-only).

I considered creating a new PyTypeObject for each wrapped function, but I didn't tried yet since I think this may be overkill...

Is there a nice way to tell Python the doc string to be returned for each wrapped function ?

Upvotes: 1

Views: 244

Answers (1)

kjrkvc
kjrkvc

Reputation: 115

Of course there is a way. Just follow the documentation: https://docs.python.org/3.5/c-api/structures.html#c.PyMethodDef

Basically what you need to do is this:

static PyMethodDef YourMethods[] = {
  { "yourMethod", yourMethod, METH_NOARGS, 
    "Your docstring for the method/function." },
   0};

And then just include YourMethods in your PyModuleDef, and that's it.

Upvotes: 1

Related Questions