首页 > 解决方案 > Python 2 和 Python 3 内置 all() 函数的行为不同

问题描述

以下代码:

a = None
b = None
all([a, b, a > b]) # Returns False in python 2 but TypeError in python 3

python 3中的错误:

TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'

似乎 python 2 版本是短路的,但 python 3 版本不是。是这样吗?为什么会这样?它是一个错误吗?我应该报告吗?

我已经在 Python 2.7.17、3.6.9 和 3.8.2 中测试过这段代码

标签: pythonbuilt-innonetypeshort-circuiting

解决方案


短路无关紧要。在执行之前评估整个列表all

Python 2 在比较方面更加宽容。在 Python 2 中,您可以<在字符串和整数、许多不同类型的对象之间使用,并且None不会出错。在 Python 3 中,规则被收紧了,因此您只能<在具有明确含义的情况下使用。

如果您需要的功能是

a and b and a > b

那么我建议你使用它。对于该表达式,a > b不会评估 ifabis None


推荐阅读