检查代码与 Python 2 和 3 的兼容性 [英] Checking code for compatibility with Python 2 and 3

查看:53
本文介绍了检查代码与 Python 2 和 3 的兼容性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何自动化方法来测试代码是否与 Python 2 和 3 兼容?我看过很多关于如何编写与两者兼容的代码的文档,但没有关于自动检查的文档.基本上是一种用于版本之间兼容性的 linting,而不是语法/样式.

Is there any automated way to test that code is compatible with both Python 2 and 3? I've seen plenty of documentation on how to write code that is compatible with both, but nothing on automatically checking. Basically a kind of linting for compatibility between versions rather than syntax/style.

我想过使用两个解释器运行测试,或者运行像 six2to3 这样的工具并检查没有输出;不幸的是,前者要求您的测试覆盖率达到 100%,我认为后者要求您拥有有效的 Python 2 代码,并且只会发现与 Python 3 兼容的问题.

I have thought of either running tests with both interpreters or running a tool like six or 2to3 and checking that nothing is output; unfortunately, the former requires that you have 100% coverage with your tests and I would assume the latter requires that you have valid Python 2 code and would only pick up issues in compatibility with Python 3.

有什么东西可以完成这项任务吗?

Is there anything out there that will accomplish this task?

推荐答案

除了在两个版本上运行代码并发现不一致之外,没有万无一失"的方法可以做到这一点.话虽如此,CPython2.7 有一个 -3 标志,它(根据 man 页面)说:

There is no "fool-proof" way of doing this other than running the code on both versions and finding inconsistencies. With that said, CPython2.7 has a -3 flag which (according to the man page) says:

警告 2to3 无法轻松修复的 Python 3.x 不兼容性.

Warn about Python 3.x incompatibilities that 2to3 cannot trivially fix.

至于您拥有有效的 python3 代码并且想要将其向后移植到 python2.x 的情况——您可能实际上并不想这样做.python3.x 是未来.在一般情况下,这很可能是一个非常痛苦的问题.开始使用 python3.x 的很多原因是因为你可以访问各种很酷的新功能.尝试重新编写已经依赖于很酷的新功能的代码通常会非常困难.尝试升级 python2.x 包以在 python3.x 上运行比反过来做要好得多.

As for the case where you have valid python3 code and you want to backport it to python2.x -- You likely don't actually want to do this. python3.x is the future. This is likely to be a very painful problem in the general case. A lot of the reason to start using python3.x is because then you gain access to all sorts of cool new features. Trying to re-write code that is already relying on cool new features is frequently going to be very difficult. Your much better off trying to upgrade python2.x packages to work on python3.x than doing things the other way around.

这篇关于检查代码与 Python 2 和 3 的兼容性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆