Building complex Python objects¶
Implementation of HPy_BuildValue.
Note: HPy_BuildValue is a runtime helper functions, i.e., it is not a part of the HPy context, but is available to HPy extensions to incorporate at compile time.
HPy_BuildValue creates a new value based on a format string from the values passed in variadic arguments. Returns HPy_NULL in case of an error and raises an exception.
HPy_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.
Building complex values with HPy_BuildValue is more convenient than the equivalent code that uses more granular APIs with proper error handling and cleanup. Moreover, HPy_BuildValue provides straightforward way to port existing code that uses Py_BuildValue.
HPy_BuildValue always returns a new handle that will be owned by the caller. Even an artificial example ‘HPy_BuildValue(ctx, “O”, h)’ does not simply forward the value stored in ‘h’ but duplicates the handle.
Supported Formatting Strings¶
Numbers¶
i (int) [int]
Convert a plain C int to a Python integer object.
l (int) [long int]
Convert a C long int to a Python integer object.
I (int) [unsigned int]
Convert a C unsigned int to a Python integer object.
k (int) [unsigned long]
Convert a C unsigned long to a Python integer object.
L (int) [long long]
Convert a C long long to a Python integer object.
K (int) [unsigned long long]
Convert a C unsigned long long to a Python integer object.
f (float) [float]
Convert a C float to a Python floating point number.
d (float) [double]
Convert a C double to a Python floating point number.
Collections¶
(items) (tuple) [matching-items]
Convert a sequence of C values to a Python tuple with the same number of items.
[items] (list) [matching-items]
Convert a sequence of C values to a Python list with the same number of items.
{key:value} (dict) [matching-items]
Convert a sequence of C values to a Python dict with the same number of items.
Misc¶
O (Python object) [HPy]
Pass an untouched Python object represented by the handle.
If the object passed in is a HPy_NULL, it is assumed that this was caused because the call producing the argument found an error and set an exception. Therefore, HPy_BuildValue will also immediately stop and return HPy_NULL but will not raise any new exception. If no exception has been raised yet, SystemError is set.
Any HPy handle passed to HPy_BuildValue is always owned by the caller. HPy_BuildValue never closes the handle nor transfers its ownership. If the handle is used, then HPy_BuildValue creates a duplicate of the handle.
S (Python object) [HPy]
Alias for ‘O’.