Chapter 2. Porting
Several tools are available to somewhat automate porting of code from Python 2.x to Python 3.x. Using any of these will generally require some manual developer attention during the process, but in many cases a fairly small degree of such attention.
There are two approaches to consider when porting code:
-
Is this a one time transition? For in-house code, it is almost certainly a better idea to make a clean break and commit to the Python 3.x series (after sufficient testing, code review, etc.). Even FLOSS libraries may want to make the jump as well, perhaps maintaining parallel versions for a certain period of time (e.g., a
Foolib
andFoolib3
might both get updated for a while). -
Do you want to instead create a version-neutral codebase that will run on both Python 2.x and Python 3.x? It is possible to use compatibility shims to write such code while still fairly elegantly falling back or falling forward with differences in features. However, using these shims will probably require writing some code in a manner less than the most idiomatic style for a Python series, at least at times.
Basically, if you want to make a clean break, use the tool 2to3
which
comes bundled with recent Python versions, in both series. If you want
to create version-neutral code, use the support libraries six
or
Python-Futures
. There was, for a while, a short-lived project called
3to2
to backport code already written for Python 3.x; however, it has not been well maintained, and using ...
Get Picking a Python Version: A Manifesto now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.