Returning a tuple of multipe objects in Python C API
Asked Answered
V

3

10

I am writing a native function that will return multiple Python objects

PyObject *V = PyList_New(0);
PyObject *E = PyList_New(0);
PyObject *F = PyList_New(0);

return Py_BuildValue("ooo", V, E, F);

This compiles fine, however, when I call it from a Python program, I get an error:

SystemError: bad format char passed to Py_BuildValue

How can this be done correctly?

EDIT: The following works

PyObject *rslt = PyTuple_New(3);
PyTuple_SetItem(rslt, 0, V);
PyTuple_SetItem(rslt, 1, E);
PyTuple_SetItem(rslt, 2, F);
return rslt;

However, isn't there a shorter way to do this?

Velma answered 16/8, 2010 at 23:25 Comment(3)
You also need to remember to decrement the reference count on V, E and F (Py_DECREF(V);, etc.) after calling Py_BuildValue, since Py_BuildValue increments the reference count of any object used with the O format specifier (see docs.python.org/c-api/arg.html#Py_BuildValue). Otherwise, the lists will never be freed, and you have a memory leak.Countertenor
Thanks for the suggestion. I am returning Py_BuildValue("NNN", V, E, F) which does not increment the reference count.Velma
I have a question when will V,E,F be free (equivalent Py_DECREF) after return to Python implementation? Thanks!Emmieemmit
M
13

I think it wants upper-case O? "OOO", not "ooo".

Matland answered 16/8, 2010 at 23:29 Comment(1)
Maybe you have also to add parenthesis to make python understand that you want to build a tuple : return Py_BuildValue("(OOO)", V, E, F);Ahrens
M
2

As Ned Batcheder noted Py_BuildValue requires Uppercase and paranthesis to create the Tuple

Py_BuildValue("(OOO)", V, E, F);

Another option to achieve the same results is PyTuple_Pack

PyTuple_Pack(3, V, E, F);
Montoya answered 6/2, 2021 at 12:27 Comment(0)
N
-6

Use Cython.

return V, E, F
Nodose answered 17/8, 2010 at 10:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.