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)?
-
3I assume you read stackoverflow.com/questions/1104823/… ?boardrider– boardrider2016年08月08日 14:35:40 +00:00Commented Aug 8, 2016 at 14:35
1 Answer 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.
answered Dec 20, 2016 at 15:13
MSeifert
154k41 gold badges356 silver badges378 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py