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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:36:39  来源:igfitidea点击:

Boolean identity == True vs is True

pythonbooleanjythoncpythonpypy

提问by All Workers Are Essential

It is standard convention to use if foo is Nonerather than if foo == Noneto 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 == Truerather 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 Trueis 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 Truewould 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 Trueshould generally be used to determine whether foohas a true-like value.

注意:我知道Python 布尔值 - if x:, vs if x == True, vs if x is True。但是,它只地址是否if fooif foo == Trueif 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 fooreally is a boolean and of value True, use the isoperator.

如果你想确保它foo真的是一个 boolean 和 value True,请使用is运算符。

Otherwise, if the type of fooimplements 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 iswith the built-in constants True, Falseand None.

根据经验,您应该始终使用is内置常量True,FalseNone

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, iswill be faster than ==since the latter must honor types' custom __eq__implementations, while iscan 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 Truewould yield different results from if 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

查看这篇文章,了解计算结果FalseEvaluation 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 boolis a subclass of int, and that Truehas 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, 1or 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 foois a boolean (and you can thus use if foo), or you know that foois 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 Trueand 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 Truein 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_