Python 布尔标识 == 真 vs 为真
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27276610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Boolean identity == True vs is True
提问by All Workers Are Essential
It is standard convention to use if foo is None
rather than if foo == None
to test if a value is specifically None
.
使用if foo is None
而不是if foo == None
测试值是否是特定的标准约定None
。
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
(不仅仅是一个类似真值的值),是否有任何理由使用if foo == True
而不是if foo is True
?这是否因 CPython(2.x 和 3.x)、Jython、PyPy 等实现而异?
Example: say True
is used as a singleton value that you want to differentiate from the value 'bar'
, or any other true-like value:
示例: sayTrue
用作要与 value'bar'
或任何其他类似 true的值区分开的单例值:
if foo is True: # vs foo == True
...
elif foo == 'bar':
...
Is there a case where using if foo is True
would yield different results from if foo == True
?
是否存在使用if foo is True
会产生不同结果的情况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.
注意:我知道Python 布尔值 - if x:, vs if x == True, vs if x is True。但是,它只地址是否if foo
,if foo == True
或if foo is True
一般应被用来确定是否foo
有一个真正般的价值。
UPDATE: According to PEP 285§ Specification:
更新:根据PEP 285§ 规范:
The values False and True will be singletons, like None.
值 False 和 True 将是单例,如 None。
采纳答案by Ferdinand Beyer
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?
如果您想确定一个值是否完全为 True(不仅仅是一个类似 true 的值),是否有任何理由使用 if foo == True 而不是 if foo is True?
If you want to make sure that foo
really is a boolean and of value True
, use the is
operator.
如果你想确保它foo
真的是一个 boolean 和 value True
,请使用is
运算符。
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.
否则,如果 的foo
实现自己的类型,__eq__()
在与 比较时返回真值True
,您可能会得到意想不到的结果。
As a rule of thumb, you should always use is
with the built-in constants True
, False
and None
.
根据经验,您应该始终使用is
内置常量True
,False
和None
。
Does this vary between implementations such as CPython (2.x and 3.x), Jython, PyPy, etc.?
这是否因 CPython(2.x 和 3.x)、Jython、PyPy 等实现而异?
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).
理论上,is
会比==
后者更快,因为后者必须尊重类型的自定义__eq__
实现,同时is
可以直接比较对象身份(例如,内存地址)。
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.
我不知道各种 Python 实现的源代码,但我假设它们中的大多数可以通过使用一些内部标志来优化魔术方法的存在,所以我怀疑你不会注意到速度差异在实践中。
回答by acushner
edit:regarding:
编辑:关于:
Is there a case where using
if foo is True
would yield different results fromif foo == True
?
是否存在使用
if foo is True
会产生不同结果的情况if foo == True
?
there is a case, and it's this:
有一个案例,它是这样的:
In [24]: 1 is True
Out[24]: False
In [25]: 1 == True
Out[25]: True
additionally, if you're looking to use a singleton as a sentinel value, you can just create an object:
此外,如果您希望使用单例作为标记值,您可以创建一个对象:
sentinel_time = object()
def f(snth):
if snth is sentinel_time:
print 'got em!'
f(sentinel_time)
you don't want to use if var == True:
, you really want if var:
.
你不想使用if var == True:
,你真的想要if var:
。
imagine you have a list. you don't care if a list is "True
" or not, you just want to know whether or not it's empty. so...
想象你有一个清单。您不在乎列表是否为“ True
”,您只想知道它是否为空。所以...
l = ['snth']
if l:
print l
check out this post for what evaluates to False
: Evaluation of boolean expressions in Python
查看这篇文章,了解计算结果False
:Evaluation of boolean expressions in Python
回答by bruno desthuilliers
is there any reason to use if foo == True rather than if foo is True?"
是否有任何理由使用 if foo == True 而不是 if foo is True?”
>>> d = True
>>> d is True
True
>>> d = 1
>>> d is True
False
>>> d == True
True
>>> d = 2
>>> d == True
False
Note that bool
is a subclass of int
, and that True
has the integer value 1
. To answer your question, if you want to check that some variable "is exactly True", you have to use the identity operator is
. Butthat's really not pythonic... May I ask what's your real use case - IOW : why do you want to make a difference between True
, 1
or any 'truth' value ?
请注意,bool
是 的子类int
,并且True
具有整数值1
。要回答您的问题,如果您想检查某个变量是否“完全正确”,则必须使用标识运算符is
。但这真的不是 pythonic ......我可以问你真正的用例是什么 - IOW:你为什么要在True
,1
或任何“真实”值之间有所作为?
回答by Kevin
Most of the time, you should not care about a detail like this. Either you already know that foo
is a boolean (and you can thus use if foo
), or you know that foo
is something else (in which case there's no need to test). If you don't know the types of your variables, you may want to refactor your code.
大多数时候,你不应该关心这样的细节。要么您已经知道这foo
是一个布尔值(因此您可以使用if foo
),要么您知道这foo
是其他东西(在这种情况下无需测试)。如果您不知道变量的类型,则可能需要重构代码。
But if you really need to be sure it is exactly True
and nothing else, use is
. Using ==
will give you 1 == True
.
但是,如果您真的需要确保它完全正确True
而不是其他任何东西,请使用is
. 使用==
会给你1 == True
。
回答by Mark Ransom
Here's a test that allows you to see the difference between the 3 forms of testing for True:
这是一个测试,可让您查看 True 的 3 种测试形式之间的差异:
for test in ([], [1], 0, 1, 2):
print repr(test), 'T' if test else 'F', 'T' if test == True else 'F', 'T' if test is True else 'F'
[] F F F
[1] T F F
0 F F F
1 T T F
2 T F F
As you can see there are cases where all of them deliver different results.
如您所见,在某些情况下,它们都提供了不同的结果。
回答by kadee
Never use is True
in combination with numpy (and derivatives such as pandas):
切勿is True
与 numpy(以及 Pandas 等衍生产品)结合使用:
In[1]: import numpy as np
In[2]: a = np.array([1, 2]).any()
In[4]: a is True
Out[4]: False
In[5]: a == True
Out[5]: True
This was unexpected to me as:
这出乎我的意料,因为:
In[3]: a
Out[3]: True
I guess the explanation is given by:
我想解释是:
In[6]: type(a)
Out[6]: numpy.bool_