Updated almost 9 years ago by Knödlseder Jürgen

Python 2.x versus Python 3.x

Overview

Citing https://wiki.python.org/moin/Python2orPython3, Python 2.x is legacy, Python 3.x is the present and future of the language. Having said this, most distribution still come today with Python 2.x, while some new distributions now feature Python 3.x. Obviously, GammaLib needs to support both. Most of the compatibility work will be done by SWIG, but there are a number of special features the developer has to be aware of.

Here a couple of rules to follow:
  • Never use print "My text" in a Python script, use print("My text"). print() is a function in Python.
  • ...

Division

Python 3.x introduces two different division types: true division and floor division. In Python 2.x, division of two integers gave an integer, in Python 3.x it gives a floating point value. To get the old behavior back, floor division indicated by the floor division operator // should be used, i.e.

a = 1
b = 2
int_div = a // b

In Python 2.x, each class supporting the unary or binary division had the __idiv__ or __div__ methods implemented. In Python 3.x, __idiv__ or __div__ do not exist anymore but are now replaced by __itruediv__ or __truediv__ for true division and __ifloordiv__ or __floordiv__ for floor division.

Unfortunately, up to now SWIG (version 3.0.2) does not seem to support the two Python 3.x division types, and the operator/= results in the Python 2.x __idiv__ method that is not recognized by Python 3.x. To make the Python interface both compatible to Python 2.x and Python 3.x, both the __idiv__ and __itruediv__ methods should be implemented for unary division, and both the __div__ and __truediv__ methods should be implemented for binary division. As example, the following extension exists for GSkymap:

// Python 2.x operator/=
GSkymap __idiv__(const GSkymap& map) {
    self->operator /=(map);
    return (*self);
}
// Python 3.x operator/=
GSkymap __itruediv__(const GSkymap& map) {
    self->operator /=(map);
    return (*self);
}

For more reading on this topic, see http://legacy.python.org/dev/peps/pep-0238/. For a discussion about the SWIG fix, see https://github.com/swig/swig/pull/136.

Links

Here some relevant links concerning Python:

Also available in: PDF HTML TXT