我正在開發Python 3 C擴展。Python C擴展中的True * args和** kwargs
我可以得到等價的或任意的位置或關鍵字參數嗎?
例如,在Python,我可以這樣寫:
def fun(name, parent, *args, **kwargs):
# do something with name and parent
# do something with args and kwargs
pass
但我不能找到一個簡單的等同於C的同時,我們可以完美地寫函數與PyObject* args
和PyObject* 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 */
}
A 「手冊」 的方法,我能想到看起來大致是:
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
}
'args'和'kwargs'都不是特別的,只是傳統的元組和字典! – cdonts