【发布时间】:2015-01-30 06:53:41
【问题描述】:
考虑以下示例代码:
data = []
try:
print data[0]
except IndexError as error:
print error.message
代码在语法上没有任何错误(使用 Python2.7),除了如果你运行 python with warnings turned on,你会看到 DeprecationWarning:
$ python -W always test.py
test.py:5: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6
print error.message
list index out of range
仅供参考,这是因为.message was deprecated since python2.6 and removed in python3。
现在,我想通过使用静态代码分析工具找到项目中在任何异常实例上调用.message 的所有位置。作为最终目标,我计划将此检查作为日常构建、测试和代码质量检查任务的一部分运行,如果仍在使用该语法,则会引发错误。
有可能吗?是pylint、pyflakes或其他代码分析工具能做到的吗?
我发现pep8 tool 实现了几个类似的检查,例如has_key() 使用检查:
$ cat test.py
my_dict = {}
print my_dict.has_key('test')
$ pep8 test.py
test.py:2:14: W601 .has_key() is deprecated, use 'in'
作为替代解决方案,我可以将所有警告视为错误(如建议的 here)并使我的测试失败,但这有其缺点:
- 我无法修复来自第三方软件包的其他弃用警告
- 严格来说,这需要100%的覆盖率,很难维护
【问题讨论】:
标签: python python-2.7 static-code-analysis deprecation-warning