Best Practices for Compatible Python 2 and 3 Code

Bob, Wed 22 March 2017, Tools

2to3, 2vs3, caniusepython3, coverage, future, futurize, pip, porting, python-modernize, Requests, six, tox, Werkzeug

95% of most popular Python packages support Python 3. Maybe you are lucky and get to start fresh using Python 3. However as of last year Python 2.7 still reigns supreme in pip installs and a lot of places 2.x is the only version you get to work in. I think writing Python 2 and 3 compatible code is an important skill, so lets check what it entails.

Python 2.x is legacy, Python 3.x is the present and future of the language - Python2orPython3 wiki

Summary Best Practices

The best place to start is the HOWTO: Porting Python 2 Code to Python 3 which nicely summarizes the important:

The future and syntax

Why it matters

It might take extra lines of code and be less idiomatic, but if on 2.x you probably have to migrate at some point. Python 2.7 will not be maintained past 2020.

Also if you release a package, doing a bit of extra effort might increase the amount of users of your software. Randy Olson's pip install analysis made me think.

This article only scratched the surface. Now is a good time to become familiar with Python porting. I learned some tricks writing this article, hopefully it gets you started too. The amount of resources available is impressive. One final site / book: Supporting Python3.

Good luck and let us know in the comments what imcompatible code you had to deal with, we like to hear your story ...

Keep Calm and Code in Python!

-- Bob