1.8 Keyword Parameters for Extension Functions 扩展模块的关键字参数
The PyArg_ParseTupleAndKeywords()function is declared as follows:
PyArg_ParseTupleAndKeywords()函数是以以下的形式声明的:
int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict, char *format, char *kwlist[], …);
The argand formatparameters are identical to those of the PyArg_ParseTuple()function. The kwdict parameter is the dictionary of keywords received as the third parameter from the Python runtime. The kwlistparameter is a NULL-terminated list of strings which identify the parameters; the names are matched with the typeinformation from formatfrom left to right. On success, PyArg_ParseTupleAndKeywords()returns true, otherwise it returns false and raises an appropriate exception.
arg和format参数与PyArg_ParseTuple()函数中是同样的。kwdict参数是一个关键字的字典,是从Python运行环境中接收到的第三个参数。kwdict参数是一个以NULL表示终止的字符串列表,列表中的字符串标识的是关键字参数;关键字的名字自左向右地与从format接收到的类型信息相匹配。匹配成功时PyArg_ParseT- upleAndKeywords()返回true,否则将返回false并抛出适当的异常。
Note:Nested tuples cannot be parsed when using keyword arguments! Keyword parameters passed in which are not present in the kwlistwill cause TypeErrorto be raised.
注意:使用关键字参数时,嵌套元组无法被解析!传入未出现于kwlist的关键字参数,会引发TypeError抛出。
Here is an example module which uses keywords, based on an example by Geoff Philbrick (philbrick@hks.com):
这有一个使用了关键字参数的例子,是基于Geoff Philbrick (philbrick@hks.com)的一个例子:
#include "Python.h"
static PyObject *
keywdarg_parrot(PyObject *self, PyObject *args, PyObject *keywds)
{
int voltage;
char *state = "a stiff";
char *action = "voom";
char *type = "Norwegian Blue";
static char *kwlist[] = {"voltage", "state", "action", "type", NULL};
if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss", kwlist, &voltage, &state, &action, &type))
return NULL;
printf("– This parrot wouldn’t %s if you put %i Volts through it.\n", action, voltage);
printf("– Lovely plumage, the %s — It’s %s!\n", type, state);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef keywdarg_methods[] = {
/* The cast of the function is necessary since PyCFunction values
* only take two PyObject* parameters, and keywdarg_parrot() takes
* three.
*/
{
"parrot", (PyCFunction)keywdarg_parrot, METH_VARARGS | METH_KEYWORDS,
"Print a lovely skit to standard output."},
{NULL, NULL, 0, NULL} /* sentinel */
};
void
initkeywdarg(void)
{
/* Create the module and add the functions */
Py_InitModule("keywdarg", keywdarg_methods);
}
No comments:
Post a Comment