Extending and Embedding Python, Release 3.9.5 (continued from previous page) 2.1.9 Building Arbitrary Values This function is the counterpart to$_{PyArg_ParseTuple()}$ . It is declared as follows: PyObject *Py_BuildValue( const char *format, ...); It recognizes a set of format units similar to the ones recognized by$_{PyArg_ParseTuple()}$ , but the arguments (which are input to the function, not output) must not be pointers, just values. It returns a new Python object, suitable for returning from a C function called from Python. One difference with$_{PyArg_ParseTuple()}$ : while the latter requires its first argument to be a tuple (since Python argument lists are always represented as tuples internally),$_{Py_BuildValue()}$ does not always build a tuple. It builds a tuple only if its format string contains two or more format units. If the format string is empty, it returns $_{None}$; if it contains exactly one format unit, it returns whatever object is described by that format unit. To force it to return a tuple of size 0 or one, parenthesize the format string. Examples (to the left the call, to the right the resulting Python value): 15 2.1. Extending Python with C or C++ const char *state ="a stiff"; const char *action ="voom"; const char *type ="Norwegian Blue"; static char *kwlist[] ={ "voltage ","state","action","type",NULL }; if (!PyArg_ParseTupleAndKeywords(args, keywds, "i|sss ", kwlist, &voltage, &state,&action,&type)) return NULL ; printf( "-- This parrot wouldn't %s if you put %i Volts through it. ", action, voltage); printf( "-- Lovely plumage, the %s -- It's %s! ", type, state); Py_RETURN_NONE; } static PyMethodDef keywdarg_methods[] ={ /* The cast of the function is necessary since PyCFunction values * only take two PyObject* parameters, and keywdarg_parrot() takes * three. */ { "parrot", (PyCFunction)( void (*)( void ))keywdarg_parrot, METH_VARARGS| METH_ ↪ → KEYWORDS, "Print a lovely skit to standard output. "}, { NULL ,NULL ,0,NULL } /* sentinel */ }; static structPyModuleDef keywdargmodule={ PyModuleDef_HEAD_INIT, "keywdarg", NULL , -1 , keywdarg_methods }; PyMODINIT_FUNC PyInit_keywdarg( void ) { return PyModule_Create(&keywdargmodule); }