《扩展和嵌入python解释器》1.8 扩展函数的关键字参数

1.8 扩展函数的关键字参数

PyArg_ParseTupleAndKeywords()函数声明如下:

 

int PyArg_ParseTupleAndKeywords(PyObject *arg, PyObject *kwdict,
                                char *format, char *kwlist[], ...);

argformat参数与PyArg_ParseTuple()函数完全相同。 kwdict参数是关键字字典作为从Python运行时接收到的第三个参数, kwlist参数是一个NULL结尾的用来标识参数的字符串; kwlist名称和format中类型信息匹配从左到右。函数PyArg_ParseTupleAndKeywords())成功返回true,否则返回false并产生合适的异常。

Note::当使用关键字参数时,嵌套的元组不能被解析。传入的关键字参数不能在kwlist里表示将产生TypeError异常。

下面是使用关键字的例子模块,基于Geoff Philbrick()的例子。

 

#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);
}
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值