Skip to content

Instantly share code, notes, and snippets.

@JolleJolles
Created November 8, 2018 09:08
Show Gist options
  • Save JolleJolles/dde2354d4f00322836d70660fc665bb9 to your computer and use it in GitHub Desktop.
Save JolleJolles/dde2354d4f00322836d70660fc665bb9 to your computer and use it in GitHub Desktop.
Short list of key changes to make python 2.7 code compatible for python 2.7 and 3.x

## Making python 2 and 3 compatible:

Import above everything

from future import print_function

All print statements have to have brackets, like

print("sint")

Exceptions need to be in brackets as well

raise ValueError("dodgy value")

Integer division

####python 2 currently rounds down, i.e. 2/3==0 not 0.66, while python 3 does true division ####rounding down in both python 2 and 3 is 2//3, thus with two slashes ####to run true division in python 2 and 3 from future import division # (at top of module)

and then use simply one slashassert 3 / 2 == 1.5

so far I have circumvented this problem by using a dot after integer (e.g. 2. instead of 2). So maybe try and fix this

Imports relative to a package

####Suppose the package is: mypackage/ init.py submodule1.py submodule2.py ####and the code below is in submodule1.py:

Python 2 only:

import submodule2

Python 2 and 3:

from . import submodule2

Change all ranges to list(range) as otherwise it will use the range from python3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment