[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Py_BuildValue vs PyTuple_Pack vs PyTuple_New

20.10.20 18:05, Marco Sulla ????:
> I read these three C api functions, They are similar, because they all
> construct a tuple[1].
> IMHO, Py_BuildValue is more simple to use than PyTuple_Pack that is more
> simple to use than PyTuple_New.
> Where to use one or the other? What's the relative performance of the three
> functions?

Py_BuildValue is the most powerful (it can creates not only tuple, it
can create items from V integers, strings, etc, it can decrement
refcount), but it is slower. It is used when the performance less
important than saving few lines of code. PyTuple_Pack() is convenient
when you create a tuple from constant number of Python objects. It is a
good compromise with readability and performance. PyTuple_New is used
for creating a variable-size tuple. In combination with macros
PyTuple_SET_ITEM it can be use3d as more verbose but slightly more
efficient version of PyTuple_Pack. But PyTuple_SET_ITEM is not in the
limited API.

For your case I suggest to use PyTuple_Pack (unless you find that
PyTuple_New+PyTuple_SET_ITEM is critically more performant).