Originally Published: Wednesday, 25 July 2001 Author: Ken McDonald and Darryl Harms
Published to: develop_articles/Development Articles Page: 2/4 - [Printable]

Chapter 11, The Quick Python Book: Modules and Scoping rules

Linux.com is proud to feature the following article on Python modules and scooping from the book "The Quick Python Book", published by Manning Press. Python, many people say is one of the most elegant programming languages in existence: read on to find out why. Also don't miss Linux.com's companion Live chat with Ken McDonald and Darryl Harms today at 11:00 am PDT on IRC in channel #live on irc.openprojects.net.

A first Module  << Page 2 of 4  >>

11. 2 A first module

The best way to learn about modules is probably to make one, so... Create a text file called mymath. py, and in that text file, enter the following Python code (if you are using IDLE, just select New window (figure 11.1) from the File menu and start typing):

File mymath. py

""" mymath -our example math module""" 
   pi = 3.14159
 def area( r): 
   """ area( r): return the area of a circle with radius r.""" 
   global pi 
   return( pi * r * r) 

Figure 1

Save this for now in the directory where your Python executable is. This code merely defines a constant and a function. The .py filename suffix is mandatory for all Python code files. It identifies that file to the Python interpreter as consisting of Python source code. As with functions, we have the option of putting in a document string as the first line of our module. Now start up the Python Shell, and type

>>> pi 
Traceback (innermost last): 
File "< stdin>", line 1, in ? 
NameError: pi 
>>> area( 2) 
Traceback (innermost last): 
File "< stdin>", line 1, in ? 
NameError: area 

In other words, Python doesn't have the constant pi or the function area built in.

Now, type:

>>> import mymath 
>>> pi 
Traceback (innermost last): 
File "<stdin>", line 1, in ? 
NameError: pi 
>>> mymath. pi
==> 3.14159
>>> mymath. area(2)
==> 12.56636 
>>> mymath.__ doc__ 
==> 'mymath -our example math module' 
>>> mymath. area.__ doc__ 
==> 'area( r): return the area of a circle with radius r. '

We've brought in the definitions for pi and area from the mymath. py file, using the import statement (which automatically adds on the .py suffix when it searches for the file defining the module named "mymath"). However, the new definitions aren't directly accessible; typing pi by itself gave an error, and typing area(2) by itself would give an error. Instead, we access pi and area by prepending them with the name of the module that contains them. This guarantees name safety. There may be another module out there which also defines pi (maybe the author of that module thinks that pi is 3.14, or 3.14159265), but that is of no concern. Even if that other module were imported, its version of pi will be accessed by othermodulename. pi, which is different from mymath. pi. This form of access is often referred to as qualification (i. e., the variable pi is being qualified by the module mymath). We may also refer to pi as an attribute of mymath.

Definitions within a module can access other definitions within that module, without prepending the module name. The mymath.area function accesses the mymath.pi constant as just pi.

If we want to, we can also specifically ask for names from a module to be imported in such a manner that we don't have to prepend them with the module name. Type:

>>> from mymath import pi 
>>> pi 
==> 3.14159 
>>> area(2) 
Traceback (innermost last): 
 File "<stdin>", line 1, in ? 
NameError: area 

The name pi is now directly accessible because we specifically requested it using from module import name.

The function area still needs to be called as mymath. area, though, because it was not explicitly imported.

You may want to use the basic interactive mode or IDLE's Python Shell to incrementally test a module as you are creating it. However, if you change your module on disk, retyping the import command will not cause it to load again. You need to use the reload function for this.

>>> import mymath 
>>> reload(mymath) 
==> <module 'mymath'> 

When a module is reloaded (or imported for the first time), all of its code is parsed. So a syntax exception will be raised if an error is found. On the other hand, if everything is okay, a .pyc file (i. e. mymath. pyc) containing Python byte code will be created.

Reloading a module does not put you back into exactly the same situation as when you start a new session and import it for the first time. However, the differences will not normally cause you any problems. If interested, you can look up reload in the built-in functions section of the Python Language Reference to find the details.

Of course, modules don't need to be used from the interactive Python shell. They can also be imported into scripts, or other modules for that matter; just enter suitable import statements at the beginning of your program file. Also, internally to Python, the interactive session and a script are considered modules as well.

To summarize:

  • A module is a file defining Python objects.
  • If the name of the module file is modulename. py, then the Python name of the module itself is modulename.
  • A module named modulename can be brought into use with the "import module-name" statement. After this statement is executed, objects defined in the module can be accessed as modulename.objectname.
  • Specific names from a module can be brought directly into your program using the "from modulename import objectname" statement. This makes objectname accessible to your program without needing to prepend it with modulename, and is useful for bringing in names that are often used.

11. 3 The import statement

There are three different forms of the import statement. The most basic,

import modulename 

simply searches for a Python module of the given name, parses its contents, and makes it available. The importing code can make use of the contents of the module, but any references by that code to names within the module must still be prepended with the module name. If the named module is not found, an error will be generated. Exactly where Python looks for modules will be discussed shortly.

The second form permits specific names from a module to be explicitly imported into the code:

from modulename import name1, name2, name3, . . . 

Each of name1, name2, and so forth, from within modulename are made available to the importing code; code after the import statement can make use of any of name1, name2, name3, . . ., without prepending the module name.

Finally, there's a general form of the from . . . import . . . statement:

from modulename import * 

The '* ' stands for all of the names in modulename. This imports almost all names from modulename, and makes them available to the importing code, without the necessity of prepending the module name.

This particular form of importing should be used with some care. If two modules both define a name, and you import both modules using this form of importing, you'll end up with a name clash. It also makes it more difficult for readers of your code to determine where names you are using originate. When using either of the two previous forms of the import statement you give your reader explicit information about where they are from.

However, some modules (such as Tkinter and types, which will be covered later) name their functions such as to make it obvious where they originate, and to make it quite unlikely there will be name clashes. It is standard practice to use this form to import them.

A first Module  << Page 2 of 4  >>