Which 2to3 fixers output valid Python 2 code?

微笑、不失礼 提交于 2019-12-05 09:30:43
EmberQuill

From What's New In Python 3.0:

It is not recommended to try to write source code that runs unchanged under both Python 2.6 and 3.0; you’d have to use a very contorted coding style, e.g. avoiding print statements, metaclasses, and much more. If you are maintaining a library that needs to support both Python 2.6 and Python 3.0, the best approach is to modify step 3 above by editing the 2.6 version of the source code and running the 2to3 translator again, rather than editing the 3.0 version of the source code.

That link up there is a pretty good one, since it also lists most of the major new features and changes in 3.0

As for your question, the closest thing I can find to what you're asking for is Six, which is not a converter or fixer, but rather a compatibility library that handles a lot of the contorted coding for you. That said, I don't know how well it works, and it would require a lot of changes to your existing code to take advantage of it anyway.

The main problem is that Python 3.x changed so many fundamental aspects of the syntax that it's almost impossible for the same code to work the same way on both 3.x and 2.x without a compatibility layer of some kind. Python 2's strings aren't the same as Python 3's strings. The same goes for integers, and Python 3 doesn't even have a long type any more (Python 3 ints are what longs used to be, and the old Python 2 int is gone). Many built-in functions and attributes have been renamed or modified, and most of the syntax has been changed or cleaned up in ways that completely break backwards-compatibility.

Porting code to Python 3 with 2to3 explains a bit about 2to3 and what it does, and the sheer volume of syntax changes listed should hopefully be enough to explain why the resultant code won't work with Python 2.x any more.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!