This is a simple example from the python documentation (http://docs.python.org/extending/extending.html):
static PyObject * spam_system(PyObject *self, PyObject *args) { const char *command; int sts; if (!PyArg_ParseTuple(args, "s", &command)) return NULL; sts = system(command); return Py_BuildValue("i", sts); }
If I want to pass an additional boolean parameter to the function - what's the "correct" way to do it?
There doesn't seem to be a bool option to pass to PyArg_ParseTuple(). So I thought of the following:
Any of these preferable? Other options?
There are two Boolean. values: True and False. Values in Python can be compared using comparison operations, and Boolean logic can be formulated with the use of logic operations.
The logical operators and, or and not are also referred to as boolean operators. While and as well as or operator needs two operands, which may evaluate to true or false, not operator needs one operand evaluating to true or false. Boolean and operator returns true if both operands return true.
4 maybe there's a way to get any type of variable and get its truth value (i.e an empty array will is falsy etc.) which is what python function usually do.
Yes: (from Python/C API Reference)
int PyObject_IsTrue(PyObject *o)
Returns 1 if the object o is considered to be true, and 0 otherwise. This is equivalent to the Python expression not not o. On failure, return -1.
EDIT. To answer the actual question, I think approach 1 is correct, because int really is the corresponding type in C. Approach 4 is good, but if you document your function as taking a bool, you are not obligated to accept just any object. Explicit type checks as in 3 without a reason are frowned upon in Python. Conversion to another Python object as in 2 does not help your C code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With