We're back after a server migration that caused effbot.org to fall over a bit harder than expected. Expect some glitches.

How do I use Py_BuildValue() to create a tuple of arbitrary length?

You can’t. Use PyTuple_New instead, and fill it with objects using PyTuple_SetItem — note that this “eats” a reference count of the inserted object, so if you’re inserting an existing object, you have to Py_INCREF it.

result = PyTuple_New(count);
if (!result)
    return NULL;

for (i = 0; i < count; i++) {
    value = PyInt_FromLong(i);
    if (!value) {
        return NULL;
    PyTuple_SetItem(result, i, value);

Lists have similar functions PyList_New and PyList_SetItem. Note that you must set all the tuple items to some value before you pass the tuple to Python code — PyTuple_New initializes them to NULL, which isn’t a valid Python value.

CATEGORY: extending