Monday, 24 August 2009

Porting Python programs to 3.x

Today I 'av mainly been thinking about how to upgrade existing Python programs so that they can be easily ported to Python 3.x. The advice on the Python website is:

  1. Write tests (we all know that anyway).
  2. Run tests and make sure they pass. Lets hope that you are using the unit test package and perhaps even a coverage tool so that you know something about the quality of the tests.
  3. Run python2.6 with the -3 option to find out what changes you can make to your source to ease the transition. The idea is to stick with 2.6/7 until you are ready to jump to 3.x (assuming that all 3rd party packages are available).
  4. Make the recommended changes either manually or perhaps by using the 2to3 translation tool. (2to3 can be run with specific options e.g 2to3 -f has_key will just change has_key to in.)
  5. Re-run tests.
  6. Do a full conversion to 3.x and see if tests still work. (Again keeping main source configured for 2.6/7)
Well thats the theory. For my part I have taken this advice and am helping with the porting of the Pmw package here.

I have also been wondering why the same has not been done for the whole of the Python standard library. Tkinter in particular is full of has_key and callable. This is a pity as it obscures problems in local code.

I also realised that the output format of 2to3 is quite verbose. I have produced a summary tool here to get a shorter easier to read output as shown below:





$ python2.6 -3 All.py 2>&1 | python2.6 -m ppande.py3stats
/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py
DeprecationWarning: callable() not supported in 3.x; use hasattr(o, '__call__')
[1050, 3237]
DeprecationWarning: dict.has_key() not supported in 3.x; use the in operator
[1903, 1914, 1939, 1967, 2438, 2441]
/Users/steve/pmw_fixes/Pmw/Pmw_0_0_0/lib/PmwEntryField.py
DeprecationWarning: builtin_function_or_method inequality comparisons not supported in 3.x
[114, 147]
Total errors: 10
Summary:
DeprecationWarning: builtin_function_or_method inequality comparisons not supported in 3.x
DeprecationWarning: callable() not supported in 3.x; use hasattr(o, '__call__')
DeprecationWarning: dict.has_key() not supported in 3.x; use the in operator



No comments:

Post a Comment