title: How can one use PyArg_ParseTupleAndKeywords to parse a tuple with optional arguments as well as keywords?
body: <p>I've looked everywhere, but I can't find an example of <code>PyArg_ParseTupleAndKeywords()</code> being used with a tuple &mdash; containing optional arguments &mdash; <em>and</em> keywords. The closest I've found is <a href="https://stackoverflow.com/questions/10625865/how-does-pyarg-parsetupleandkeywords-work/10625987#10625987">this question</a>, 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.</p>
  
  <p>Suppose I'm trying to parse the following parameters:</p>
  
  <ul>
  <li>numpy array of doubles (mandatory)</li>
  <li>numpy array of doubles (optional, no keyword)</li>
  <li>optional keyword arguments:
  
  <ul>
  <li>k1 => numpy array of doubles</li>
  <li>k2 => integer</li>
  <li>k3 => double</li>
  <li>k4 => Python class instance</li>
  </ul></li>
  </ul>
  
  <p>It seems like I should be doing something like</p>
  
  <pre><code>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, &amp;arg1, &amp;PyArray_Type, &amp;arg2, &amp;PyArray_Type, &amp;k1, &amp;PyArray_Type, &amp;k2, &amp;k3, &amp;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;
  }
  </code></pre>
  
  <p>Other places I've looked, but without finding much help:</p>
  
  <ul>
  <li><a href="https://docs.python.org/2/extending/extending.html" rel="nofollow noreferrer">https://docs.python.org/2/extending/extending.html</a></li>
  <li><a href="https://docs.python.org/2/c-api/arg.html" rel="nofollow noreferrer">https://docs.python.org/2/c-api/arg.html</a></li>
  <li><a href="http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html" rel="nofollow noreferrer">http://docs.scipy.org/doc/numpy-1.10.1/user/c-info.how-to-extend.html</a></li>
  </ul>
  
  <p>What is the appropriate way to use <code>PyArg_ParseTupleAndKeywords()</code>?</p>