【问题标题】:Specifying Python function signature in C/API在 C/API 中指定 Python 函数签名
【发布时间】:2016-08-07 20:46:32
【问题描述】:

在纯 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)

【问题讨论】:

标签: python python-c-api


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多