Specifying Python function signature in C/API

与世无争的帅哥 提交于 2021-01-27 13:01:35

问题


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)?


回答1:


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.



来源:https://stackoverflow.com/questions/38818400/specifying-python-function-signature-in-c-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!