PyArg_ParseTuple, test for SEVERAL possibilities

Skip Montanaro skip at pobox.com
Mon Jun 7 21:11:37 CEST 2004


    Torsten> 1. I'd like to check for a list of "int"s and i don't
    Torsten> know how many int's are in this array, it could be
    Torsten> 0 to 8, all of this would make sense.

    Torsten> How can i check for that?

How about:

    /* define my int args with desired default values */
    int i1 = 0, i2 = 0, ..., i8 = 0;

    if (!PyArg_ParseTuple(args, "|iiiiiiii", &i1, &i2, ..., &i8) {
        return NULL;
    }

    /* do stuff with i1 ... i8 */

    Torsten> 2. I'd like to check for SEVERAL possibilities of
    Torsten> argument string, e.g. for "sss" and "li" and "[3]".
    Torsten> How can i do that without error message when the
    Torsten> parameters do not match?

Just call PyArg_ParseTuple repeatedly until one variant works.  Call
PyErr_Clear() before each call.  After the last possibility if it still
fails, suppress that last error and raise your own error which will make
more sense than the generic message in the raised exception.

    Torsten> 3. Not really related to ParseTuple, but to BuildValue:
    Torsten> I want to create a list as a return value.  I want to
    Torsten> create the size of that list at runtime.
    Torsten> For example if i want to return a list with up to
    Torsten> 200 values, how can i build that at runtime?

This would be

    mylist = PyList_New(0);
    if (!mylist) { handle error }

    /* append up to 200 values to the list */

In other words, you probably don't want to you Py_BuildValue for this.

Skip




More information about the Python-list mailing list