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

时间:2016-08-07 20:46:33

标签: python python-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)

1 个答案:

答案 0 :(得分:2)

您可以通过以http://127.0.0.1:5000/temperature/20003可以提取它们的方式将其添加到函数docstring中来包含签名(至少它适用于Python 3.4 +):

inspect

注意我已经发布了一个更完整的答案here,可以更深入地解释规则和机制。