我需要检查其他团队编写的函数是否返回 True
或 None
。
我想检查身份,而不是平等。
我不清楚使用 in
时会发生什么类型的检查。 if 结果 (True, None):
的行为类似于以下哪一项?
如果结果为 True 或结果为 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
来自docs :
For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y)
in 运算符测试相等性和同一性,其中任何一个为 true 都将返回 True
。我的印象是您只使用 bool 值和None
。在这种有限的情况下,in
运算符的行为与其他两个代码段相同。
但是,您说您想要进行身份验证。所以我建议你明确地使用它,这样你的代码的意图和期望就很清楚了。此外,如果被调用函数中存在错误,并且它返回 bool 值或 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
关于python - 测试同一性与测试是否在元组中不同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40855998/