Python if x:, vs if x == True, vs if x is True
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20420934/
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
if x:, vs if x == True, vs if x is True
提问by ssast
Apologies if this has been asked before, but I have searched in vain for an answer to my exactquestion. Basically, with Python 2.7, I have a program running a series of geoprocessing tools, depended on what is reqested via a series of True/False variables that the user adjusts in the script e.g.
抱歉,如果之前有人问过这个问题,但我徒劳地搜索了我的确切问题的答案。基本上,使用 Python 2.7,我有一个运行一系列地理处理工具的程序,这取决于用户在脚本中调整的一系列 True/False 变量所要求的内容,例如
x = True
if x:
run function
However, I have now discovered that x does not need to be literally "True" for the function to run. For example:
但是,我现在发现 x 不需要字面上的“真”才能运行该函数。例如:
In: x = True
if x:
print True
Out: True
In: x = 123
if x:
print True
Out: True
In: x = 'False'
if x:
print True
Out: True
In: x = False
if x:
print True
Out:
So any value other than False appears to evaluate to True, which would not be the case for if x == Trueor if x is True. Seeing as PEP 8 strongly recommends only using the if x:variant, can anybody explain why this behaviour occurs? It seems that if x: is more a test for "if x is not False" or "if x exists". With that in mind, I believe I should be using if x is True: in this case, despite what PEP 8 has to say.
因此,除 False 以外的任何值似乎都计算为 True,如果x == True或x 为 True则情况并非如此。看到 PEP 8 强烈建议只使用if x:变体,有人能解释为什么会发生这种行为吗?似乎 if x: 更像是对“if x is not False”或“if x exists”的测试。考虑到这一点,我相信我应该使用 if x is True:在这种情况下,尽管 PEP 8 必须说。
Kind regards
亲切的问候
采纳答案by Steve Jessop
The following values in Python are false in the context of ifand other logical contexts:
Python 中的以下值在if和其他逻辑上下文中为 false :
FalseNone- numeric values equal to 0, such as
0,0.0,-0.0 - empty strings:
''andu'' - empty containers (such as lists, tuples and dictionaries)
- anything that implements
__bool__(in Python3) to returnFalse, or__nonzero__(in Python2) to returnFalseor0. - anything that doesn't implement
__bool__(in Python3) or__nonzero__(in Python2), but does implement__len__to return a value equal to 0
FalseNone- 等于 0 的数值,例如
0,0.0,-0.0 - 空字符串:
''和u'' - 空容器(例如列表、元组和字典)
- 任何实现
__bool__(在 Python3 中)返回False,或__nonzero__(在 Python2 中)返回False或0。 - 任何没有实现
__bool__(在 Python3 中)或__nonzero__(在 Python2 中),但确实实现__len__返回等于 0 的值的任何东西
An object is considered "false" if any of those applies, and "true" otherwise, regardless of whether it's actually equal to or identical with Falseor True
如果其中任何一个适用,则对象被认为是“假”,否则被认为是“真”,无论它是否实际上等于或等同于False或True
Now, if you've arranged that xis necessarily one of the objects Trueor False, then you can safely write if x. If you've arranged that the "trueness" of xindicates whether or not to perform the operation, regardless of type, then you can safely write if x. Where you can write that you should prefer to do so, since it's cleaner to read.
现在,如果您已经安排了x它必然是对象之一Trueor False,那么您可以安全地编写if x. 如果您已经安排了“真实性”x指示是否执行操作,无论类型如何,那么您可以安全地编写if x. 你可以在哪里写你应该更喜欢这样做,因为它读起来更干净。
Normally, if it is allowed for xto take the value Truethen you're in one of those two cases, and so you would not write if x is True. The important thing is to correctly document the meaning of x, so that it reflects the test used in the code.
通常,如果允许x取值,True那么您处于这两种情况之一,因此您不会写if x is True. 重要的是正确记录 的含义x,以便它反映代码中使用的测试。
Python programmers are expected to know what's considered true, so if you just document, "runs the function if xis true", then that expresses what your original code does. Documenting it, "runs the function if x is True" would have a different meaning, and is less commonly used precisely because of the style rule in PEP8 that says to test for trueness rather than the specific value True.
Python程序员应该知道什么被认为是真的,所以如果你只是记录,“如果x为真则运行函数”,那么这表达了你的原始代码的作用。记录它,“如果运行函数x is True”会有不同的含义,并且不太常用,正是因为 PEP8 中的样式规则说测试真实性而不是特定值True。
However, if you wanted the code to behave differently in the case where xis an empty container from the case where it is None, then you would write something like if x is not None.
但是,如果您希望代码在x空容器和空容器的情况下表现不同None,那么您可以编写类似if x is not None.
回答by Jakob Bowyer
x = 'False'
x = 123
Are both True
都是 True
The document explains other values.
该文档解释了其他值。
As far as the PEP8 reason, its far more semantic to read if this_file_is_green
至于 PEP8 的原因,它的语义要读得多 if this_file_is_green
回答by U2EF1
Other falsey values include 0, '', []. You should just use the if x:version.
其他 falsey 值包括0、''、[]。您应该只使用该if x:版本。
回答by 6502
The ability to say
有能力说
if x:
...
is considered a feature. You can also specify when the test should be considered to pass or not for user defined classes (just define the method __nonzero__in Python 2.x or __bool__in Python 3).
被认为是一个特征。您还可以为用户定义的类指定何时应考虑通过或不通过测试(只需__nonzero__在 Python 2.x 或__bool__Python 3 中定义方法)。
For example for strings and containers like lists, dictionaries or sets the test if x ...means "if x is not empty".
例如,对于字符串和容器(如列表、字典或集合),测试if x ...意味着“如果 x 不为空”。
Note that the rationale is not that this allows less code to write, but that resulting code is easier to read and to understand.
请注意,其基本原理不是这允许编写更少的代码,而是生成的代码更易于阅读和理解。
If you like instead to write if x is True ...have you considered to go farther down that path to if (x is True) is True ...or if ((x is True) is True) is True ...? :-)
如果你喜欢而不是写if x is True ...你认为走的更远了这条道路,以if (x is True) is True ...或if ((x is True) is True) is True ...?:-)
回答by Michael Geary
It goes without saying that you should write code that does what you need. But in most cases, you simply don't need to say == Trueor is True, because you don't need to distinguish Truefrom other "truthy" values. So it's recommended to leave that out for simplicity.
不用说,您应该编写满足您需要的代码。但在大多数情况下,您根本不需要说== True或is True,因为您不需要与True其他“真实”值区分开来。因此,为了简单起见,建议将其省略。
The case where you definitely should use == Trueor is Trueis when you doneed to distinguish Truefrom other truthy values.
在这里你绝对应该使用的情况下,== True或者is True是当你做需要区分True与其他truthy值。
In your example, do you care about the difference between Trueand 123? That would tell you which way to code it.
在您的示例中,您是否关心True和之间的区别123?那会告诉你用哪种方式编码。
One thing about coding == Trueor is True: it will raise a minor red flag when other developers read your code. They won't think it's wrong, they will just wonder why it's there and will want to know why it's important to treat Truedifferently from other truthy values in this particular case.
关于编码== True或的一件事is True:当其他开发人员阅读您的代码时,它会引发轻微的危险信号。他们不会认为这是错误的,他们只是想知道它为什么存在,并且想知道为什么True在这种特殊情况下区别对待其他真实值很重要。
In other words, if you don't need it, it's best not to use it.
换句话说,如果你不需要它,最好不要使用它。
回答by santaklaus
In Python 2.7, if a:and if a==Trueare not giving the same output for values different to 1. Here are some snippets of code to demonstrate the different behaviors:
在 Python 2.7 中,if a:并且if a==True不会为不同于 1 的值提供相同的输出。以下是一些代码片段来演示不同的行为:
with a=1
和 a=1
a=1
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (1,True)
a=1
if a:
print (a,"True")
else:
print (a,"Not True")
output> (1, True)
with a=2
和 a=2
a=2
if a:
print (a,"True")
else:
print (a,"Not True")
output> (2, True)
a=2
if a==True:
print (a,"True")
else:
print (a,"Not True")
output> (2, Not True)

