我需要检查另一个团队编写的函数是否返回True
或None
.
我想检查身份,而不是平等。
我不清楚使用in
. 以下哪项的if result in (True, None):
行为是这样的?
if result is True or result is None:
if result or result == None:
我需要检查另一个团队编写的函数是否返回True
或None
.
我想检查身份,而不是平等。
我不清楚使用in
. 以下哪项的if result in (True, None):
行为是这样的?
if result is True or result is None:
if result or result == None:
不,它们不一样,因为身份测试是in
操作员所做工作的一个子集。
if result in (True, None):
与此相同:
if result == True or result is True or result == None or result is None:
# notice that this is both #1 and #2 OR'd together
从文档:
对于 list、tuple、set、frozenset、dict 或 collections.deque 等容器类型,表达式 x in y 等价于 any(x is e or x == e for e in y)
in 运算符测试相等性和身份,任何一个为真都将返回True
。我的印象是您只使用布尔值和None
. 在这种有限的情况下,in
运算符的行为将与您的其他两个片段相同。
但是,您说要进行身份检查。所以我建议你明确地使用它,这样你的代码的意图和它的期望就很清楚了。此外,如果被调用函数中存在错误并且它返回的不是 boolean or None
,则使用in
运算符可以隐藏该错误。
我建议你的第一个选择:
if result is True or result is None:
# do stuff
else:
# do other stuff
或者,如果您感到防御:
if result is True or result is None:
# do stuff
elif result is False:
# do other stuff
else:
# raise exception or halt and catch fire
您想使用身份运算符(is) 而不是成员运算符 (in):
> 1 == True
True
> 1 is True
False
> 1 in (True, None)
True
这是对@skrrgwasme 答案的“TL;DR”补充 :)