对于我们正在编写的小型测试框架,我试图提供一些实用功能。
其中一个应该等价于 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
orwhile
condition or as operand of the Boolean operations below.
not
只是反转相同的真值;所以如果 x
被上述规则认为是 true not x
返回 False
,否则返回 True
。
注意:在 Python 2 中,内置名称 False
和 True
可以通过设置全局变量来屏蔽:
>>> True = False
>>> True
False
因此 is
身份测试也可能被该重新分配所愚弄。 Python 3 制作了 False
和 True
关键字。
您的效用函数不需要使用 bool(x) is True
或 bool(x) is False
。您只需要 bool(x)
和 not bool(x)
,因为这些已经产生了 True
和 False
对象。 bool()
和 not
无法返回任何其他内容,使用 is True
或 is False
非常有用多余的。
最后但同样重要的是,尽量不要重新发明测试轮。 Python标准库自带一个unittest
库;它同时具有 assertTrue
和 assertFalse
函数,以及 implementation of these functions只需使用 if
和 if not
。
关于python - `if x:` 完全等同于 `if bool(x) is True:` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38510964/