Question

This question already has an answer here:

So with the final releases of Python 3.0 (and now 3.1), a lot of people are facing the worry of how to upgrade without losing half their codebase due to backwards incompatibility.

What are people's best tips for avoiding the many pitfalls that will almost-inevitably result from switching to the next-generation of python?

Probably a good place to start is "use 2to3 to convert your python 2.x code to 3.x" :-)

Was it helpful?

Solution

First, this question is very similar to How are you planning on handling the migration to Python 3?. Check the answers there.

There is also a section in the Python Wiki about porting applications to Python 3.x

The Release Notes for python 3.0 contains a section about porting. I'm quoting the tips there:

  1. (Prerequisite:) Start with excellent test coverage.
  2. Port to Python 2.6. This should be no more work than the average por from Python 2.x to Python 2.(x+1). Make sure all your tests pass.
  3. (Still using 2.6:) Turn on the -3 command line switch. This enables warnings about features that will be removed (or change) in 3.0. Run your test suite again, and fix code that you get warnings about until there are no warnings left, and all your tests still pass.
  4. Run the 2to3 source-to-source translator over your source code tree. (See 2to3 - Automated Python 2 to 3 code translation for more on this tool.) Run the result of the translation under Python 3.0. Manually fix up any remaining issues, fixing problems until all tests pass again.

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.

OTHER TIPS

I write a free book about this. You can read it here:

http://python3porting.com/

In short:

  1. Make sure all your third party libraries are available for Python 3.
  2. Prepare your code by removing common ambiguities:
    • Use // if you really want integer division.
    • Make sure you flag binary files with the 'b' flag when you open them, to clearly indicate if you mean the data to be binary or not.
  3. The higher your test coverage is, the better.
  4. Make sure it runs without warnings under "Python 2.7 -3".
  5. Now run 2to3.
  6. Fix any bugs.

That's it, more or less.

Without a really compelling reason to upgrade, I would stick with what works. I looked at upgrading the scripts I use daily and it was too much work for no benefit that I could see.

"If it ain't broke, don't fix it!"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top