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¶
import numpy- all functions or variable can be accessed using
numpy.- i.e.
numpy.pi
- i.e.
- protects against namespace collisions
- what if two different modules have a variable
piand they refer to different things?
- what if two different modules have a variable
- typing
numpy.gets old
- all functions or variable can be accessed using
import numpy as npnp.pi- still projects against namespace collisions
- if you actually used
np = 7or something, you would break the import - some people use
import numpy as N, but I think this is risky- you can never use
Nanywhere in your code without messing things up
- you can never use
Four ways to import (#3)¶
from numpy import pi, arangepiandarangenow work by themselves withoutnumpy.ornp.piandarangeare 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)¶
from numpy import *- load everything in the
numpymodule into the global namespace
- load everything in the
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
%pylaboption spyderdoes this style of import if you click the option in settings to loadnumpyandpylab
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
