Chapter 22. Moving from Python 2 to Python 3
This chapter covers
- Using Python 2.6 for preliminary testing
- Converting using 2to3
- Testing and common pitfalls
- Using the same code base for Python 2 and 3
We’ve dealt with only the syntax and features of Python 3.x so far in this book. That was deliberate, because we feel that Python 3.x is a distinct improvement over early versions of Python and it’s where future development should occur. On the other hand, it’s not always possible to make a clean break from the past. For the foreseeable future, many situations will call for dealing with legacy Python 2.x code. This chapter discusses how you can migrate older Python 2.x code to Python 3.x.
Several changes from Python 2.x to 3.x broke compatibility between the two versions. Some of them were obvious but easy to fix, such as the change of the print statement to the print function or the change of the input function to behave the way that the old raw_input function did. Other changes were more subtle, and more posed sneakier problems: the change of strings to be Unicode by default with the addition of a bytes type to hold unencoded byte values, returning iterators and views instead of lists from functions like range and a dictionary’s keys method, differences in handling exceptions, and the addition of sets come to mind, to name a few.
Table 22.1 illustrates some of the representative differences between Python 2.x and 3.x code.