In this post, we’ll discuss how to configure the behavior of the division operator in Python 2.7 and IPython to behave like the Python 3.x counterpart.

We’ll call the division in Python 2.x “classic” or “old.” It does division in the C sense: an integer divided by an integer yields an integer, rounding down if needed.

The “new” division in Python 3.x instead computes the true division result. In this case, an integer divided by an integer yields a float. The floor division can be accessed in a new operator “//” as in:

>>> 1 // 2
0

To allow for a transition period, two compatibility features are provided. First, module developers can add

from __future__ import division

to the top of any .py file to indicate that “/” should mean true division in that file.

In addition, the Python interpreter can be passed a flag to indicate the desired division behavior:

-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew

So for example, we can run:

$ python2.7 -Qnew
...
>>> 1/2
0.5

But what about IPython? There isn’t a corresponding flag on the ipython script, yet. In discussing adding this feature to IPython, Fernando Perez provided a useful tip for accomplishing this using the IPython configuration files.

To begin, you’ll need to create an IPython profile by running

$ ipython profile create

Then edit the configuration file, which for me was located at ~/.config/ipython/profile_default/ipython_config.py, and uncomment and add the following: