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 (like the StringIO module) are described below. The description of all of the standard library changes is contained in PEP 3108.

Porting the SalishSeaTools Package

This section describes the types of changes that had to be made to port the SalishSeaTools Package (including the nowcast codebase) 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.

Change print Statements to print() Functions

print was a statement in Python 2. It is a function in Python 3. So, code like:

print 'red is clockwise'

has to be changed to:

print('red is clockwise')

Change cStringIO.StringIO Imports to io.StringIO

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. So, 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.

The mock library that was developed as a separate, stand-alone library for Python 2 is included in the standard library in Python 3. So, instead from it like:

from mock import (

the Python 3 import looks like:

from unittest.mock import (

Also, because 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 (requirements.txt, requirements.pip, environment.yaml, etc.).