Skip to content

Python Compatibility

matteobachetti edited this page Feb 12, 2015 · 17 revisions

For PINT, we recommend following the writing portable code practices as specified by the Astropy project.

Python 2/3 compatibility

A good start for Python 2/3 compatibility is adding the following line at the very top of each Python source:

#!python
from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

This will allow to write Python 2 code with part of the new syntax introduced by Python 3, making the code automatically compatible with the two versions.

Division

While in Python 2 the division between two integers is always the integer part of the result (4/3 = 1), in Python 3 this has changed and now division correctly returns a float if required (4/3=1.33333...). Adding division to the __future__ imports makes division work this way also in Python 2. To execute an integer division, the operation is now a//b.

Print function

print is a function in Python 3. This means that while in Python 2 (without the print_function import from 'future') we wrote

#!python
print a

we now write

#!python
print(a)

print a, (a way not to print a newline at the end of the print) now becomes print(a, end='').

print >>fobj, a now becomes print(a, file=fobj)

Unicode

TBD

Import

TBD