Skip to content

Latest commit

 

History

History
125 lines (80 loc) · 3.63 KB

porting_to_python3.rst

File metadata and controls

125 lines (80 loc) · 3.63 KB

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

Porting the :pySalishSeaTools Package

This section describes the types of changes that had to be made to port the SalishSeaToolsPackage (including the :pynowcast 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 :pyTabError 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 :pyprint Statements to :pyprint Functions

:pyprint 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 :pycStringIO.StringIO Imports to :pyio.StringIO

In Python 2 :pyStringIO 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 :pyStringIO class has been moved to the :pyio 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

:pymock Library is in the Standard Library

Note

This is only applicable to test suite code.

The :pymock 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 (
     Mock,
     patch,
 )

the Python 3 import looks like:

from unittest.mock import (
     Mock,
     patch,
 )

Also, because :pymock 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.).