Python 嵌入——如何从 C/C++ 获取 if() 真值测试行为?

发布于 2024-07-19 03:10:22 字数 264 浏览 6 评论 0原文

我正在尝试编写一个函数来返回给定 PyObject 的真值。 该函数应该返回与 if() 真值测试相同的值——空列表和字符串为 False 等。 我一直在查看 python/include 标头,但没有找到任何似乎可以做到这一点的东西。 我最接近的是 PyObject_RichCompare(),第二个值是 True,但返回 False,例如“1”== True。 是否有一个方便的函数来执行此操作,或者我是否必须针对一系列类型进行测试并对每种可能的类型进行特殊情况测试? if()的内部实现做了什么?

I'm trying to write a function to return the truth value of a given PyObject. This function should return the same value as the if() truth test -- empty lists and strings are False, etc.
I have been looking at the python/include headers, but haven't found anything that seems to do this. The closest I came was PyObject_RichCompare() with True as the second value, but that returns False for "1" == True for example.
Is there a convenient function to do this, or do I have to test against a sequence of types and do special-case tests for each possible type? What does the internal implementation of if() do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

子栖 2024-07-26 03:10:22

这不是在 object.h: 中吗

PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);

Isn't this it, in object.h:

PyAPI_FUNC(int) PyObject_IsTrue(PyObject *);

?

轻许诺言 2024-07-26 03:10:22

使用

int PyObject_IsTrue(PyObject *o)
如果对象 o 被认为是 true,则返回 1,否则返回 0。 这相当于 Python 表达式 not not o。 失败时返回-1。

(来自 Python/C API 参考手册

Use

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.

(from Python/C API Reference Manual)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文