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

PyBites Python Tips

Do you want to get 250+ concise and applicable Python tips in an ebook that will cost you less than 10 bucks (future updates included), check it out here.

Get our Python Tips Book

"The discussions are succinct yet thorough enough to give you a solid grasp of the particular problem. I just wish I would have had this book when I started learning Python." - Daniel H

"Bob and Julian are the masters at aggregating these small snippets of code that can really make certain aspects of coding easier." - Jesse B

"This is now my favourite first Python go-to reference." - Anthony L

"Do you ever go on one of those cooking websites for a recipe and have to scroll for what feels like an eternity to get to the ingredients and the 4 steps the recipe actually takes? This is the opposite of that." - Sergio S

Get the book