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 found is this question, but the answer isn't particularly helpful. Most examples seem to have the keywords as the optional arguments, but it seems like the tuple should be able to contain optional arguments as well.
Suppose I'm trying to parse the following parameters:
- numpy array of doubles (mandatory)
- numpy array of doubles (optional, no keyword)
- optional keyword arguments:
- k1 => numpy array of doubles
- k2 => integer
- k3 => double
- k4 => Python class instance
It seems like I should be doing something like
static PyObject* pymod_func(PyObject* self, PyObject* args, PyObject* kwargs) {
static char* keywords[] = {"k1", "k2", "k3", "k4", NULL};
PyObject *arg1, *arg2, *k1, *k4
PyObject *arr1, *arr2, *karr1;
double *k3;
int *k2;
PyArg_ParseTupleAndKeywords(args, kwargs, "O!|O!OidO", keywords, &arg1, &PyArray_Type, &arg2, &PyArray_Type, &k1, &PyArray_Type, &k2, &k3, &k4);
arr1 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
if (arr1 == NULL) return NULL;
arr2 = PyArray_FROM_OTF(arg1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
// no null check, because optional
karr1 = PyArray_FROM_OTF(k1, NPY_FLOAT64, NPY_ARRAY_INOUT_ARRAY);
// again, no null check, because this is optional
// do things with k3, k2, and k4 also
return NULL;
}
Other places I've looked, but without finding much help:
- https://docs.python.org/2/extending/extending.html
- https://docs.python.org/2/c-api/arg.html
- http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html
What is the appropriate way to use PyArg_ParseTupleAndKeywords()
?