True division in IPython

As Python transitions from version 2 to version 3, the meaning of the division operator on integers is changing:

Python 2.x Python 3.x
$ python2.7
Python 2.7.2+ (...)
...
>>> 1/2
0
$ python3.2
Python 3.2.2 (...)
...
>>> 1/2
0.5

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:

# lines of code to run at IPython startup.                                                                                                                 
c.InteractiveShellApp.exec_lines = [
    'from __future__ import division'
]

We can test it out and see that it does in fact work as desired:

$ ipython
Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
Type "copyright", "credits" or "license" for more information.

IPython 0.13.dev -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: 1/2
Out[1]: 0.5
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s