Книга: Practical Programming, Fourth Edition
Назад: Chapter 6: A Modular Approach to Program Organization
Дальше: Defining Your Modules

Importing Modules

To gain access to the variables and functions from a module, you have to import it. To tell Python that you want to use functions in the module math, for example, use this import statement:

 >>>​​ ​​import​​ ​​math

Importing a module creates a new variable with that name. That variable refers to an object whose type is module:

 >>>​​ ​​type(math)
 <class 'module'>

Once you have imported a module, you can use the built-in function help to see what it contains. Here is the first part of the help output:

 >>>​​ ​​help(math)
 Help on built-in module math:
 
 NAME
  math
 
 DESCRIPTION
  This module provides access to the mathematical functions
  defined by the C standard.
 
 FUNCTIONS
  acos(x, /)
  Return the arc cosine (measured in radians) of x.
 
  The result is between 0 and pi.
 
  acosh(x, /)
  Return the inverse hyperbolic cosine of x.
 
  asin(x, /)
  Return the arc sine (measured in radians) of x.
 
  The result is between -pi/2 and pi/2.
 
 [There are many other functions not shown here.]

The statement import math creates a variable called math that refers to a module object. In that object are all the names defined in that module. Some of them refer to function objects:

Module

Great—your program can now use all the standard mathematical functions. When you attempt to calculate a square root, however, you encounter an error informing that Python is still unable to find the sqrt function:

 >>>​​ ​​sqrt(9)
 Traceback (most recent call last):
  File "<python-input-0>", line 1, in <module>
  sqrt(9)
  ^^^^
 NameError: name 'sqrt' is not defined

The solution is to tell Python explicitly to look for the function in the module math by combining the module’s name with the function’s name using a dot:

 >>>​​ ​​math.sqrt(9)
 3.0

The dot is an operator, just like + and ** are operators. Its meaning is “look up the object that the variable to the left of the dot refers to and, in that object, find the name that occurs to the right of the dot.” In math.sqrt(9), Python finds math in the current namespace, looks up the module object that math refers to, finds the function sqrt inside that module, and then executes the function call following the standard rules described in .

Modules can contain more than just functions. The module math, for example, also defines some variables, such as pi. Once the module has been imported, you can use these variables like any others:

 >>>​​ ​​import​​ ​​math
 >>>​​ ​​math.pi
 3.141592653589793
 >>>​​ ​​radius​​ ​​=​​ ​​5
 >>>​​ ​​print(​​'area is'​​,​​ ​​math.pi​​ ​​*​​ ​​radius​​ ​​**​​ ​​2)
 area is 78.53981633974483

You can even assign to variables imported from modules:

 >>>​​ ​​import​​ ​​math
 >>>​​ ​​math.pi​​ ​​=​​ ​​3
 >>>​​ ​​radius​​ ​​=​​ ​​5
 >>>​​ ​​print(​​'area is'​​,​​ ​​math.pi​​ ​​*​​ ​​radius​​ ​​**​​ ​​2)
 area is 75

Don’t do this! Changing the value of π isn’t a good idea. It’s such a bad idea that many languages allow programmers to define unchangeable constants as well as variables. As the name suggests, the value of a constant cannot be changed after it has been defined: π is always 3.14159 and a little bit, while SECONDS_PER_DAY is always 86,400. The fact that Python doesn’t allow programmers to “freeze” values like this is one of the language’s few significant flaws.

How Do You Mean, “this”?

icon indicating an aside

Try this code:

 >>>​​ ​​import​​ ​​this

(Don’t worry, it’s safe!) Enjoy the output!

Combining the module’s name with the names of its contents is safe, but it isn’t always convenient. For this reason, Python allows you to specify precisely what you want to import from a module, as shown here:

 >>>​​ ​​from​​ ​​math​​ ​​import​​ ​​sqrt,​​ ​​pi
 >>>​​ ​​sqrt(9)
 3.0
 >>>​​ ​​radius​​ ​​=​​ ​​5
 >>>​​ ​​print(​​'circumference is'​​,​​ ​​2​​ ​​*​​ ​​pi​​ ​​*​​ ​​radius)
 circumference is 31.41592653589793

This statement doesn’t introduce a variable called math. Instead, it creates the function sqrt and the variable pi in the current namespace, as if you had typed the function definition and variable assignment yourself. Restart your shell and try this:

 >>>​​ ​​from​​ ​​math​​ ​​import​​ ​​sqrt,​​ ​​pi
 >>>​​ ​​math.sqrt(9)
 Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
  math.sqrt(9)
  ^^^^
 NameError: name 'math' is not defined. Did you forget to import 'math'?
 >>>​​ ​​sqrt(9)
 3.0

Here, you don’t have a variable called math. Instead, you imported names sqrt and pi directly into the current namespace, as shown in this diagram:

From import

Direct importing of names can lead to problems when different modules provide functions that have the same name, causing a name conflict. If you import a function called spell from a module called magic (fictitious), and then you import another function called spell from the grammar module (also fictitious), the second replaces the first. It’s exactly like assigning one value to a variable and then assigning another value: the most recent assignment or import wins.

Name conflicts are the reason why it’s usually not a good idea to use import *, which brings in everything from the module at once:

 >>>​​ ​​from​​ ​​math​​ ​​import​​ ​​*
 >>>​​ ​​print(sqrt(8))
 2.8284271247461903

Although import * saves some typing, you run the risk of your program accessing the incorrect function and not working correctly.

The standard Python library comprises several hundred modules that can perform a wide range of tasks, from determining the day of the week to fetching data from websites. However, it’s far too extensive to absorb in one sitting. Knowing how to use the library effectively is one of the key factors that distinguishes good programmers from those who are less skilled.

Назад: Chapter 6: A Modular Approach to Program Organization
Дальше: Defining Your Modules