Python C扩展中的True * args和** kwargs

时间:2016-03-05 22:21:11

标签: python-3.x python-c-api python-c-extension

我正在开发Python 3 C扩展。

我可以获得等效或任意位置或关键字参数吗?

例如,在Python中,我可以写:

def fun(name, parent, *args, **kwargs):
    # do something with name and parent
    # do something with args and kwargs
    pass

但我在C中找不到简单的等价物。虽然我们可以用PyObject* argsPyObject* kwargs完美地编写函数,但我不能轻易地从任何一个(args / kwargs)“解析”名称和父级它来了。

采取:

static PyObject* myFunction(PyObject* self, PyObject* args, PyObject* kwargs) {
    char* kwds[] = {"parent", "name", NULL};
    PyObject* name = NULL;
    PyObject* parent = NULL;
    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO", kwds, &parent, &name)) {
        goto errorParseTupleAndKeywords;
    }
    /* Do something with name and parent */
    /* parent and name maybe have appeared either in args or kwargs */
    /* But I don't have any extra positional (*args) or keyword (**kwargs) here */    
}

我能想到的“手动”方法看起来大致如下:

static PyObject* myFunction(PyObject* self, PyObject* args, PyObject* kwargs) {
    PyObject* name = NULL;
    PyObject* parent = NULL;
    int inKwargs = 0;
    // Pretend to do something with parent
    if (PyDict_GetItemString(kwargs, "parent")) {
        inKwargs++;
        PyDict_DelItemString(kwargs, "parent");
    }
    // Pretend to do something with name
    if (PyDict_GetItemString(kwargs, "name")) {
        inKwargs++;
        PyDict_DelItemString(kwargs, "name");
    }
    // Not sure if -1 works here
    PyObject* newArgs = PyTuple_GetSlice(args, inKwargs, -1); // this is *args
    // the remaining kwargs can be used as **kwargs
}

1 个答案:

答案 0 :(得分:2)

在C API中,PyObject* args实际上是一个Python元组,而PyObject* kwargs实际上是一个Python字典。至少这是PyArg_ParseTupleAndKeywords internally所要求的:

int PyArg_ParseTupleAndKeywords(PyObject *args, PyObject *keywords, const char *format, char **kwlist, ...)
{
    // …
    if ((args == NULL || !PyTuple_Check(args)) ||
        (keywords != NULL && !PyDict_Check(keywords)) ||
        format == NULL ||
        kwlist == NULL)
    {
        PyErr_BadInternalCall();
        return 0;
    }

    // …
}

vgetargskeywords中该函数的实际实现也会再次声明这一点,因此您应该可以通过从对象中手动提取来替换PyArg_ParseTupleAndKeywords调用。

这意味着您可以同时使用tupledict API,也可以使用iterator protocol来迭代这些对象中的项目。