This function is the counterpart to PyArg_ParseTuple()
. It is
declared as follows:
PyObject *Py_BuildValue(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), 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.
In the following description, the quoted form is the format unit; the entry in (round) parentheses is the Python object type that the format unit will return; and the entry in [square] brackets is the type of the C value(s) to be passed.
The characters space, tab, colon and comma are ignored in format strings (but not within format units such as `s#'). This can be used to make long format strings a tad more readable.
NULL
, None
is returned.
NULL
, the length is ignored and None
is
returned.
None
) [char *]
None
) [char *, int]
int
to a Python integer object.
long int
to a Python integer object.
int
representing a character to a Python string of
length 1.
double
to a Python floating point number.
NULL
pointer, it is assumed that this was caused because the call producing
the argument found an error and set an exception. Therefore,
Py_BuildValue()
will return NULL
but won't raise an
exception. If no exception has been raised yet,
PyExc_SystemError
is set.
void *
) as its argument and should return a
``new'' Python object, or NULL
if an error occurred.
If there is an error in the format string, the
PyExc_SystemError
exception is raised and NULL
returned.
Examples (to the left the call, to the right the resulting Python value):
Py_BuildValue("") None Py_BuildValue("i", 123) 123 Py_BuildValue("iii", 123, 456, 789) (123, 456, 789) Py_BuildValue("s", "hello") 'hello' Py_BuildValue("ss", "hello", "world") ('hello', 'world') Py_BuildValue("s#", "hello", 4) 'hell' Py_BuildValue("()") () Py_BuildValue("(i)", 123) (123,) Py_BuildValue("(ii)", 123, 456) (123, 456) Py_BuildValue("(i,i)", 123, 456) (123, 456) Py_BuildValue("[i,i]", 123, 456) [123, 456] Py_BuildValue("{s:i,s:i}", "abc", 123, "def", 456) {'abc': 123, 'def': 456} Py_BuildValue("((ii)(ii)) (ii)", 1, 2, 3, 4, 5, 6) (((1, 2), (3, 4)), (5, 6))