布尔身份== True vs True [英] Boolean identity == True vs is True
问题描述
使用if foo is None
而不是if foo == None
来测试值是否明确地是None
是常规约定.
It is standard convention to use if foo is None
rather than if foo == None
to test if a value is specifically None
.
如果要确定某个值是否恰好是True
(而不仅仅是真值),是否有任何理由使用if foo == True
而不是if foo is True
?这在CPython(2.x和3.x),Jython,PyPy等实现之间是否有所不同?
If you want to determine whether a value is exactly True
(not just a true-like value), is there any reason to use if foo == True
rather than if foo is True
? Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?
示例:例如说True
用作要与值'bar'
或任何其他真值相区别的单例值:
Example: say True
is used as a singleton value that you want to differentiate from the value 'bar'
, or any other true-like value:
if foo is True: # vs foo == True
...
elif foo == 'bar':
...
是否存在使用if foo is True
会产生与if foo == True
不同的结果的情况?
Is there a case where using if foo is True
would yield different results from if foo == True
?
NOTE: I am aware of Python booleans - if x:, vs if x == True, vs if x is True. However, it only addresses whether if foo
, if foo == True
, or if foo is True
should generally be used to determine whether foo
has a true-like value.
更新:根据 PEP 285 §规范:
值False和True将是单例,如None.
The values False and True will be singletons, like None.
推荐答案
如果要确定某个值是否完全为True(而不仅仅是类似True的值),是否有任何理由使用foo == True而不是foo为True?
If you want to determine whether a value is exactly True (not just a true-like value), is there any reason to use if foo == True rather than if foo is True?
如果要确保foo
确实是一个布尔值且值为True
的布尔值,请使用is
运算符.
If you want to make sure that foo
really is a boolean and of value True
, use the is
operator.
否则,如果foo
的类型实现了自己的__eq__()
且与True
相比返回了真值,则结果可能会出乎意料.
Otherwise, if the type of foo
implements its own __eq__()
that returns a true-ish value when comparing to True
, you might end up with an unexpected result.
根据经验,应该始终将is
与内置常量True
,False
和None
一起使用.
As a rule of thumb, you should always use is
with the built-in constants True
, False
and None
.
这在CPython(2.x和3.x),Jython,PyPy等实现之间是否有所不同?
Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?
从理论上讲,is
将比==
快,因为后者必须遵守类型的自定义__eq__
实现,而is
可以直接比较对象身份(例如内存地址).
In theory, is
will be faster than ==
since the latter must honor types' custom __eq__
implementations, while is
can directly compare object identities (e.g., memory addresses).
我并不是很了解各种Python实现的源代码,但是我认为其中大多数可以通过使用一些内部标志来优化魔术方法的存在,因此我怀疑您不会注意到练习中的速度差异.
I don't know the source code of the various Python implementations by heart, but I assume that most of them can optimize that by using some internal flags for the existence of magic methods, so I suspect that you won't notice the speed difference in practice.
这篇关于布尔身份== True vs True的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!