python - 测试同一性与测试是否在元组中不同吗?

标签 python equality truthiness

我需要检查其他团队编写的函数是否返回 TrueNone

我想检查身份,而不是平等。

我不清楚使用 in 时会发生什么类型的检查。 if 结果 (True, None): 的行为类似于以下哪一项?

  1. 如果结果为 True 或结果为 None:

  2. 如果结果或结果==无:

最佳答案

不,它们不一样,因为身份测试是 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/

相关文章:

python - 从 OpenCV + Python 获取 HOG 图像特征?

javascript - 如何检查两个变量是否具有相同的引用?

php - 如何在 php 中测试数组的索引是否与数组的另一个索引相等?

python - 解析随每个 API 查询而变化的 JSON 对象

python - 可以在 PostgreSQL INSERT 语句中放置的最大 VALUES 数量是多少?

javascript - 如果 ([] == false) 为真,为什么 ([] || true) 结果为 []?

ruby - 在 ruby​​ 中,以问号结尾的方法名称是否符合真实性?

Javascript 未定义的字符串属性真实性

python - Pandas Dataframe 根据日期过滤行

javascript - 如何检查 NaN javascript 的相等性