Porting Code to Python 3¶
While there are many differences between Python 2 and Python 3 few of them impact most of the code that we write in the Salish Sea project. This section describes the types of changes that had to be made in order to convert (also known as “port”) the SalishSeaTools Package to Python 3.
If you encounter other changes that you need to make to port our code to Python 3, please feel free to add them below.
If you are interested in the details of the differences between Python 2 and Python 3 they can be found in the What’s New in Python documentation.
Part of the move to Python 3 was a reorganization of the standard library.
That means that some import need to be changed when code is ported from Python 2 to Python 3.
Specific instances of that
are described below.
The description of all of the standard library changes is contained in PEP 3108.
This section describes the types of changes that had to be made to port the SalishSeaTools Package
from Python 2.7 to Python 3.5 in October 2015.
Mixed TABs and Spaces for Indentation¶
While mixing TABs and spaces for indentation in a Python module was never a good idea,
it causes a
TabError exception to be raised when such a module is imported in Python 3.
All Python code should use spaces for indentation and the indentation levels should be 4 spaces.
print Statements to
print 'red is clockwise'
has to be changed to:
print('red is clockwise')
cStringIO.StringIO Imports to
In Python 2
StringIO class in the standard library has two implementations,
one in Python,
and a faster one in C.
The former was imported like:
from StringIO import StringIO
and the latter like:
from cStringIO import StringIO
In Python 3 the
StringIO class has been moved to the
io module and the interpreter takes care of first trying to import the faster C version or falling back to the Python version if necessary.
those imports need to be changes to:
from io import StringIO
mock Library is in the Standard Library¶
This is only applicable to test suite code.
mock library that was developed as a separate,
stand-alone library for Python 2 is included in the standard library in Python 3.
instead from it like:
from mock import ( Mock, patch, )
the Python 3 import looks like:
from unittest.mock import ( Mock, patch, )
mock is now part of the standard library,
it no longer needs to be installed separately or included in
setup.py or environment descriptions files