How Can One Use Pyarg_parsetupleandkeywords To Parse A Tuple With Optional Arguments As Well As Keywords?
I've looked everywhere, but I can't find an example of PyArg_ParseTupleAndKeywords() being used with a tuple — containing optional arguments — and keywords. The closest I've fo
Solution 1:
I think something similar to the below simplified solution should work for your scenario but it can get nasty if you have many optional args or more interesting arg types. I'm not sure if there is a better solution but I haven't been able to find one. Hopefully one day someone will post a cleaner solution.
You'll have to be clever to produce useful arg parsing error messages in more complex parsing scenarios.
static PyObject* nasty_func(PyObject* self, PyObject* args, PyObject* kwargs){
staticchar* keywords[] = {"one", "optional", "two", NULL};
staticchar* keywords_alt[] = {"one", "two", NULL};
int ok = 0;
PyObject *result = NULL;
int *one;
char *two;
int *optional;
ok = PyArg_ParseTupleAndKeywords(args, kwargs, "iis", keywords, &one, &optional, &two);
if (!ok) {
PyErr_Clear();
ok = PyArg_ParseTupleAndKeywords(args, kwargs, "is", keywords_alt, &one, &two);
if (!ok) {
PyErr_SetString(PyExc_TypeError, "Invalid args. allowed formats: 'one:i, two:s' or 'one:i, optional:i, two:s'");
returnNULL;
}
}
// do stuff with your parsed variablesreturn result;
}
Solution 2:
As of Python 3.3, you can use $
in the format string to indicate that the rest of the arguments are keyword-only, and as of Python 3.6, you can indicate a positional-only parameter by using an empty name in the keywords
argument.
So, in a sufficiently high version of Python, you can use code like:
staticchar* keywords[] = {"", "", "k1", "k2", "k3", "k4", NULL};
// [...]PyArg_ParseTupleAndKeywords(args, kwargs,
"O!|O!$O!idO", keywords,
&PyArray_Type, &arg1, &PyArray_Type, &arg2,
&PyArray_Type, &k1, &k2, &k3, &k4);
Post a Comment for "How Can One Use Pyarg_parsetupleandkeywords To Parse A Tuple With Optional Arguments As Well As Keywords?"