python - `if x:` 完全等同于 `if bool(x) is True:` 吗?

标签 python

对于我们正在编写的小型测试框架,我试图提供一些实用功能。

其中一个应该等价于 if x: 但如果那是 完全 等价于 if bool(x) is True: 然后我只能提供一个函数来检查 if x is True:if x:

那个的否定也是等价的吗? if bool(x) is False: 等于 if not x:?

最佳答案

if x: 完全等同于测试 bool 真值,是的。

来自if statement documentation :

It selects exactly one of the suites by evaluating the expressions one by one until one is found to be true (see section Boolean operations for the definition of true and false)

哪里Boolean operations section详细说明真理是如何定义的。 bool() function遵循完全相同的规则:

Return a Boolean value, i.e. one of True or False. x is converted using the standard truth testing procedure.

标准类型文档有一个 Truth Value Testing section :

Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.

not 只是反转相同的真值;所以如果 x 被上述规则认为是 true not x 返回 False,否则返回 True

注意:在 Python 2 中,内置名称 FalseTrue 可以通过设置全局变量来屏蔽:

>>> True = False
>>> True
False

因此 is 身份测试也可能被该重新分配所愚弄。 Python 3 制作了 FalseTrue 关键字。

您的效用函数不需要使用 bool(x) is Truebool(x) is False。您只需要 bool(x)not bool(x),因为这些已经产生了 TrueFalse 对象。 bool()not 无法返回任何其他内容,使用 is Trueis False 非常有用多余的。

最后但同样重要的是,尽量不要重新发明测试轮。 Python标准库自带一个unittest库;它同时具有 assertTrueassertFalse 函数,以及 implementation of these functions只需使用 ifif not

关于python - `if x:` 完全等同于 `if bool(x) is True:` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510964/

相关文章:

python - Pycharm调试 watch : Can I show directly an image

python - Pycaret - 卡在设置上()

python - 使用 if 语句的嵌套列表理解

Python:无法连接到 HTTPS URL,因为 SSL 模块不可用

Python Appengine 在执行 app.yaml 之前运行某些代码

python - GeoJson 图层在 Python Folium map 上不可见

python - 分割字符串并用成分替换原始字符串

python - Airflow 提供静态 html 目录

python - Scipy ndimage 形态学运算符使我的计算机内存 RAM (8GB) 饱和

python - 使用 Flask 中的请求连接 Bluemix 上的 Cloudant 是否有任何已知的负面影响?