![](/img/trans.png)
[英]What is the correct way (syntax) of combining boolean operators in python
[英]What is the “correct” way to pass a boolean to a Python C extension?
这是python文档(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);
}
如果我想将另一个布尔参数传递给函数 - 这是什么“正确”的方法呢?
似乎没有传递给PyArg_ParseTuple()的bool选项。 所以我想到了以下几点:
这些中哪一个更好? 其他选择?
4也许有一种方法可以获得任何类型的变量并获得其真值(即空数组将是假数据等),这是python函数通常所做的。
是的:(来自Python / C API参考 )
int PyObject_IsTrue(PyObject *o)
如果对象o被认为是真,则返回1,否则返回0。 这相当于Python表达式而不是o。 失败时,返回-1。
编辑。 为了回答实际问题,我认为方法1是正确的,因为int实际上是C中的相应类型。方法4很好,但如果你将你的函数记录为bool,你没有义务接受任何对象。 在Python中,没有理由的显式类型检查在3中是不受欢迎的。 像2中一样转换为另一个Python对象对您的C代码没有帮助。
我找到了另一种方法:
PyObject* py_expectArgs;
bool expectArgs;
PyArg_ParseTupleAndKeywords(args, keywds, (char *)"O!", (char **)kwlist, &PyBool_Type, &py_expectArgs);
expectArgs = PyObject_IsTrue(py_expectArgs);
如果错误的参数调用有“自动”异常“参数1必须是bool,而不是int”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.