在 C/API 中指定 Python 函数签名

Specifying Python function signature in C/API

在纯 Python 中定义函数时,其签名在调用 help 时可见。例如:

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

hello(name)
    Greet somebody.

>>>

在C/API中定义一个Python函数时,它的签名缺少基本信息:

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}
};

这产生:

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

hello(...)
    Greet somebody.

知道如何在 C/API 中将签名从 hello(...) 更改为 hello(name) 吗?

您可以通过将签名添加到函数文档字符串中来包含签名,inspect 可以提取它们(至少它适用于 Python 3.4+):

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

请注意,我发布了更完整的答案 here,更深入地解释了规则和机制。