1.4 Importing from Modules and Packages
15
Importing Individual Items With ball_angle.py, we just learned that the
import statement
from math import atan, pi
made the atan function and pi available to the program. To bring in even more
functionality from math, the import statement could simply have been extended
with the relevant items, say
from math import atan, pi, sin, cos, log
and so on.
Having Several Import Statements Very often, we need to import functionality
from several libraries. This is straight forward, as we may show by combining
imports from math with imports from the useful Numerical Python (or NumPy)
library, 11 named numpy in Python:
from math import atan, pi, sin, cos, log
from numpy import zeros, linspace
Right now, do not worry what the functions zeros and linspace do, we will
explain and use them soon.
Importing All Items with “Import *” The approach of importing individual items
(atan, pi, etc.) might appear less attractive if you need many of them in your
program. There is another way, though, but it should be used with care, for reasons
to be explained. In fact, many programmers will advice you not to use it at all,
unless you know very well what you are doing. With this import technique, the list
of items in the import statement is exchanged with simply a star (i.e., *). The import
statement then appears as
from some_library import *
# import all items from some_library
which with the math library reads
from math import *
# import all items from math
This will cause all items from math to be imported, however, also the ones you
do not need! So, with this “lazy” import technique, Python has to deal with a lot
of names that are not used. Like when importing individual items, items are used
without prefix.
Disadvantage: No Prefix Allows Name Conflicts! When importing so that items
are written without prefix, there is a potential problem with name conflicts. Let
us illustrate the point with a simple example. Assume that, being new to Python,
we want to write a little program for checking out some of the functions that the
language has got to offer.
Our first candidate could be the exponential function and we might like to
compute and print out e t for t = 0, 1, 2. A fellow student explains us how a function
exp in the numpy library allows our calculations to be done with a single function
11 The NumPy library (http://www.numpy.org/) is included in Anaconda. If you have not installed
Anaconda, you may have to install NumPy separately.
Précédent

- 37/350

Suivant