Py_BuildValue: make tuple with bool?
Asked Answered
B

1

12

I see in docs, that I can build tuple value with int (specifying 'i'). I need to make tuple with bool, e.g. (True, 10). How can I make such tuple with bool (what specifier needed)?

Broach answered 19/1, 2014 at 19:6 Comment(0)
M
19

There is no predefined format character for that conversion, but it is trivial to simulate one by inserting Py_True or Py_False object into the tuple, as appropriate. For example:

int i = ...;
bool b = ...;
PyObject *tuple_with_bool = Py_BuildValue("Oi", b ? Py_True: Py_False, i);

Another option is to use PyBool_FromLong to do the conversion. In that case, remember to use the N format to account for PyBool_FromLong returning a new reference:

PyObject *tuple_with_bool = Py_BuildValue("Ni", PyBool_FromLong(b), i);
Michaelson answered 19/1, 2014 at 19:13 Comment(2)
Weird nickname, but helped. Tks.Broach
The Py_RETURN_FALSE and Py_RETURN_TRUE macros are helpful too (they increment the refcount for you): docs.python.org/3/c-api/bool.htmlWitchy

© 2022 - 2024 — McMap. All rights reserved.