O'Reilly logo

Picking a Python Version: A Manifesto by David Mertz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 and Foolib3 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required