Modules are already available in Canopy's Python (PyLab) prompt, but not in a script

IPython newcomers may be confused by the following scenario.

  • You type some commands at the Canopy Python prompt, and they work great.
  • Then you copy the exact same commands to a python file, and run the file, and you get errors like "No module named...." or "name... not defined".

The solution is to understand that in each python module (e.g. in each .py file), you must always explicitly import all outside names that you wish to use in that module.

Here's why:

By default, Canopy's IPython prompt runs in "Pylab" mode (this can be changed in Canopy's Preferences menu, in the "Python" tab.)

When IPython is started in pylab mode, as in Canopy, then it starts with many imports already done behind the scenes:

import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot
from IPython.display import display
from IPython.core.pylabtools import figsize, getfigs
from pylab import *
from numpy import *

This provides almost 1000 names directly to the ipython shell, which is very convenient, but has great potential for "namespace pollution", i.e. name conflict. (There are probably names already defined that you don't even know are there and might be using for some other purpose.)

In contrast, in a python module, you must explicitly import every name which you use. This is much more robust, and since you are not constantly typing and retyping as you would do at the prompt, the extra typing is well worth it.

Related -- don't forget to call show()

When you plot in an ipython pylab session, you don't need to explicitly invoke

When you plot from a python script, you do.

Have more questions? Submit a request


Powered by Zendesk