我需要检查其他团队撰写的函数是否返回True
或None
。
我想检查身份,而不是平等。
我不清楚在使用in
时会发生什么类型的检查。 if result in (True, None):
的行为类似于以下哪一项?
if result is True or result is None:
if result or result == None:
答案 0 :(得分:3)
不,它们不一样,因为身份测试是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
来自docs:
对于容器类型,例如list,tuple,set,frozenset,dict或collections.deque,y中的表达式x等于任意(x是e或x == e表示y中的e)
in运算符测试相等性和标识,并且任何一个为true都将返回True
。我的印象是你只使用布尔值和None
。在这种有限的情况下,in
运算符的行为与其他两个代码段相同。
但是,你说你想要进行身份检查。所以我建议你明确地使用它,这样你的代码的意图和期望是明确的。此外,如果被调用函数中存在错误并且返回布尔值或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
答案 1 :(得分:0)
您想使用身份运营商(是)而不是会员运营商(in):
> 1 == True
True
> 1 is True
False
> 1 in (True, None)
True
这是对@skrrgwasme回答的“TL; DR”补充:)