Importing (Python Basics 3)

The Power of Importing

  • Python by itself is cool, but somewhat limited
  • a good deal of the power of Python comes from the huge number of modules available
    • numpy, scipy, matplotlib, os, system, time, cherrypy, ...
  • you have to import the modules to use them

Four ways to import

  1. import numpy
    • all functions or variable can be accessed using numpy.
      • i.e. numpy.pi
    • protects against namespace collisions
      • what if two different modules have a variable pi and they refer to different things?
    • typing numpy. gets old
  2. import numpy as np
    • np.pi
    • still projects against namespace collisions
    • if you actually used np = 7 or something, you would break the import
    • some people use import numpy as N, but I think this is risky
      • you can never use N anywhere in your code without messing things up

Four ways to import (#3)

  1. from numpy import pi, arange
    • pi and arange now work by themselves without numpy. or np.
      • pi and arange are now in the global namespace
    • you have to give a list of all the functions or variables you need
      • this is kind of cumbersome

Four ways to import (#4)

  1. from numpy import *
    • load everything in the numpy module into the global namespace

My old habit is to use these two lines at the beginning of every script:

from matplotlib.pyplot import *
from numpy import *
  • in some ways, this is the easiest way to not have to think about modules and make IPython easy

Four ways to import (#4)

from matplotlib.pyplot import *
from numpy import *
  • two risks:
    • namespace collisions
    • masks where things come from, making it harder to learn from or maintain code
  • some advanced Python users consider this to be poor practice
  • IPython will eventually remove the %pylab option
  • spyder does this style of import if you click the option in settings to load numpy and pylab

My Recommendation

This is the currently accepted best practice:

import matplotlib.pyplot as plt
import numpy as np
  • slightly more typing:
    • t = np.arange(0,1,0.01)
    • y = np.sin(2*np.pi*t)
  • forces you to learn what comes from where