2to3 is a Python program that reads Python 2.x source code and applies a series of fixers to transform it into valid Python 3.x code
Consider the forty fixers listed at https://docs.python.org/3.4/library/2to3.html#fixers . By design, they all output valid Python 3 code. Which output valid Python 2 code?
For example, the fixer NE that "converts the old not-equal syntax <>
to !=
" has this property, because !=
is valid Python 2 as well as Python 3.
Whereas the fixer NONZERO that "Renames __nonzero__
to __bool__
" does not have the property, because there is no function __bool__
in Python 2.7.
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.
来源:https://stackoverflow.com/questions/26223761/which-2to3-fixers-output-valid-python-2-code