Python 用 'is' 替换 '==' 来比较布尔值是否安全
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4591125/
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
Is it safe to replace '==' with 'is' to compare Boolean-values
提问by kev
I did several Boolean Comparisons:
我做了几个布尔比较:
>>> (True or False) is True
True
>>> (True or False) == True
True
It sounds like ==and isare interchangeable for Boolean-values.
这听起来像布尔值==并且is可以互换。
Sometimes it's more clear to use is
有时候用起来更清楚 is
I want to know that:
我想知道:
Are Trueand Falsepre-allocated in python?
是True和Falsepython中预分配?
Is bool(var)always return the same True(or False) with the pre-allocated True(or False)?
是bool(var)始终返回相同的True(或者False与预先分配)True(或False)?
Is it safe to replace ==with isto compare Boolean-values?
替换==与is比较布尔值是否安全?
It's not about Best-Practice.
这与最佳实践无关。
I just want to know the Truth.
我只想知道真相。
采纳答案by detly
You probably shouldn't ever need to compare booleans. If you are doing something like:
您可能永远不需要比较布尔值。如果你正在做类似的事情:
if some_bool == True:
...
...just change it to:
...只需将其更改为:
if some_bool:
...
No isor ==needed.
不需要is或==不需要。
As commenters have pointed out, there are valid reasons to compare booleans. If both booleans are unknown and you want to know if one is equal to the other, you should use ==or !=rather than isor is not(the reason is explained below). Note that this is logically equivalent to xnorand xorrespectively, which don't exist as logical operators in Python.
正如评论者指出的那样,比较布尔值是有正当理由的。如果两个布尔值都是未知的,并且您想知道一个是否等于另一个,您应该使用==or!=而不是isor is not(原因如下所述)。请注意,这在逻辑上分别等效于xnor和xor,它们在 Python 中不作为逻辑运算符存在。
Internally, there should only ever be two boolean literal objects(see also the C API), and bool(x) is Trueshould be Trueif bool(x) == Truefor any Python program. Two caveats:
在内部,应该永远只能是两个布尔字面对象(另见C API),并且bool(x) is True应该是True,如果bool(x) == True任何Python程序。两个注意事项:
- This does not meanthat
x is Trueifx == True, however (eg.x = 1). - This is true for the usual implementation of Python (CPython) but might not be true in other implementations. Hence
==is a more reliable comparison.
- 然而,这并不意味着
x is Trueifx == True,但是(例如。x = 1)。 - 这对于 Python (CPython) 的通常实现是正确的,但在其他实现中可能并非如此。因此
==是一个更可靠的比较。
回答by kevpie
Watch out for what else you may be comparing.
注意您可能会比较的其他内容。
>>> 1 == True
True
>>> 1 is True
False
True and False will have stable object ids for their lifetime in your python instance.
True 和 False 在您的 Python 实例中将在其生命周期内具有稳定的对象 ID。
>>> id(True)
4296106928
>>> id(True)
4296106928
iscompares the id of an object
is比较一个对象的id
EDIT: adding or
编辑:添加 or
Since OP is using orin question it may be worth pointing this out.
由于 OP 正在使用or有问题,因此可能值得指出这一点。
or that evaluates True:returns the first 'True' object.
或评估 True:返回第一个 'True' 对象。
>>> 1 or True
1
>>> 'a' or True
'a'
>>> True or 1
True
or that evaluates False:returns the last 'False' object
或者评估为 False:返回最后一个 'False' 对象
>>> False or ''
''
>>> '' or False
False
and that evaluates to True:returns the last 'True' object
计算结果为 True:返回最后一个 'True' 对象
>>> True and 1
1
>>> 1 and True
True
and that evaluates to False:returns the first 'False' object
计算结果为 False:返回第一个 'False' 对象
>>> '' and False
''
>>> False and ''
False
This is an important python idiom and it allows concise and compact code for dealing with boolean logic over regular python objects.
这是一个重要的 Python 习惯用法,它允许使用简洁紧凑的代码来处理常规 Python 对象上的布尔逻辑。
>>> bool([])
False
>>> bool([0])
True
>>> bool({})
False
>>> bool({False: False})
True
>>> bool(0)
False
>>> bool(-1)
True
>>> bool('False')
True
>>> bool('')
False
Basically 'empty' objects are False, 'non empty' are True.
基本上“空”对象是假的,“非空”是真。
Combining this with @detly's and the other answers should provide some insight into how to use ifand bools in python.
将此与@detly's 和其他答案相结合,应该可以对如何if在 python 中使用和bool 提供一些见解。
回答by Visionary Software Solutions
回答by Matthew Flaschen
Yes. There are guaranteedto be exactly two bools, True and False:
是的。有保证的是正好有两个boolS,真假:
Class bool cannot be subclassed further. Its only instances are False and True.
类 bool 不能进一步子类化。它的唯一实例是 False 和 True。
That means ifyou know both operands are bool, ==and isare equivalent. However, as detly notes, there's usually no reason to use either in this case.
这意味着如果您知道两个操作数都是bool,==并且is是等价的。然而,正如detly 指出的那样,在这种情况下通常没有理由使用任何一个。
回答by Senthil Kumaran
==and isare both comparison operators, which would return a boolean value - Trueor False. True has a numeric value of 1 and False has a numeric value of 0.
==和is都是比较运算符,它们将返回一个布尔值 -True或False。True 的数值为 1,False 的数值为 0。
The operator ==compare the values of two objects and objects compared are most often are the same types (int vs int, float vs float), If you compare objects of different types, then they are unequal. The operator istests for object identity, 'x is y' is true if both x and y have the same id. That is, they are same objects.
运算符==比较两个对象的值,并且比较的对象通常是相同类型(int vs int,float vs float),如果比较不同类型的对象,则它们是不相等的。运算符is测试对象身份,如果 x 和 y 具有相同的 id,则 'x is y' 为真。也就是说,它们是相同的对象。
So, when you are comparing if you comparing the return values of same type, use == and if you are comparing if two objects are same (be it boolean or anything else), you can use is.
因此,当您比较是否比较相同类型的返回值时,请使用 == 并且如果您正在比较两个对象是否相同(无论是布尔值还是其他任何对象),您可以使用is.
42 is 42is True and is same as 42 == 42.
42 is 42为真且与 相同42 == 42。
回答by Senthil Kumaran
It seems that all answers deal with Trueand Falseas defined after an interpreter startup. Before booleans became part of Python they were often defined as part of a program. Even now (Python 2.6.6) they are only names that can be pointed to different objects:
似乎所有答案都在解释器启动后处理True并False定义。在布尔值成为 Python 的一部分之前,它们通常被定义为程序的一部分。即使现在(Python 2.6.6)它们也只是可以指向不同对象的名称:
>>> True = 1
>>> (2 > 1)
True
>>> (2 > 1) == True
True
>>> (2 > 1) is True
False
If you have to deal with older software, be aware of that.
如果您必须处理较旧的软件,请注意这一点。

