Search code examples
pythonpython-c-api

Specifying Python function signature in C/API


When defining a function in pure Python, its signature is visible when calling help. For example:

>>> def hello(name):
...  """Greet somebody."""
...  print "Hello " + name
...
>>> help(hello)
Help on function hello in module __main__:

hello(name)
    Greet somebody.

>>>

When defining a Python function in C/API, though, its signature lacks basic information:

static PyObject*
mod_hello(PyObject* self, PyObject* args)
{
    const char* name;
    if (!PyArg_ParseTuple(args, "s", &name))
        return NULL;
    printf("Hello %s\n", name);
    Py_RETURN_NONE;
}

static PyMethodDef HelloMethods[] =
{
     {"hello", mod_hello, METH_VARARGS, "Greet somebody."},
     {NULL, NULL, 0, NULL}
};

This yields:

>>> help(hello)
Help on built-in function hello in module hello:

hello(...)
    Greet somebody.

Any ideas how, in C/API, to change the signature from hello(...) to hello(name)?


Solution

  • You can include the signature by prepending it to the function docstring in a way that inspect can extract them (at least it works for Python 3.4+):

    static PyMethodDef HelloMethods[] =
    {
         {"hello", mod_hello, METH_VARARGS, "hello(name, /)\n--\n\nGreet somebody."},
         {NULL, NULL, 0, NULL}
    };
    

    Note I've posted a more complete answer here that explain the rules and mechanics in some more depth.