python - 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 中测试过这段代码
解决方案
短路无关紧要。在执行之前评估整个列表all
。
Python 2 在比较方面更加宽容。在 Python 2 中,您可以<
在字符串和整数、许多不同类型的对象之间使用,并且None
不会出错。在 Python 3 中,规则被收紧了,因此您只能<
在具有明确含义的情况下使用。
如果您需要的功能是
a and b and a > b
那么我建议你使用它。对于该表达式,a > b
不会评估 ifa
或b
is None
。
推荐阅读
- python - 具有多个变量的烧瓶渲染模板
- angular7 - 在Angular 7中处理浏览器主页按钮单击事件
- java - 改造图片上传无法处理的实体错误
- javascript - SetValue GetValue Javascript ASP.NET
- c++ - C++ 调试断言失败 - Visual Studio 上的向量下标超出范围
- c++ - 如何将数组的重载运算符 [] 更改为 ()?
- ruby-on-rails - 重定向链中没有 cookie
- python - /contacts/contact 在 Django 中发送电子邮件时出现 SMTPAuthenticationError
- jsf - p:toggleSwitch 没有在 bean 中设置布尔值
- java - 如何在 Android Quiz App 中更改计时器?