< BACKMake Note | BookmarkCONTINUE >
152015024128143245168232148039199167010047123209178152124239215162146122163095031239122038

Modules and Packages

A module is a collection of classes, functions, and variables saved in a text file.

When referencing a module within your Python application, you don't need to specify the file suffix—your program text files must carry a .py extension. Modules can be written in Python or in C. No matter what option you use, you call both types of modules using the same syntax. The following syntax imports and creates the global namespace for a module:

					
import <module>

				

A module filename called yourmodule.py should be mentioned in your import clause as follows:

					
>>> import yourmodule

				

It is also possible to have multiple modules imported at the same time, using just one import statement as follows:

					
>>> import m1, m2, m3

				

Tip

An interesting fact you should know is that all the code is executed when it is imported for the first time.



Some modules are always available in Python. Others (including yours) are files and need to be imported (in most cases, those files have .py or .pyc suffixes). To be imported, a file must have been saved in one of the directories listed in the sys.path variable.

If you need your module to be runnable and importable at the same time, you need to put something like the following line of code at the end of the file:

					
If __name__ == "__main__": your_function()

				

Tip

Remember that in UNIX, you need to change the permission of a file to make it executable.



You can find out the contents of a module by typing:

					
dir(<module>)

				

For example,

					
>>> dir(math)

				

Now we will talk about packages.

A package is a collection of modules in the same directory. Package names must be subdirectories of one of the directories listed in the sys.path variable.

A package directory must have, at least, an empty __init__.py file, and it might contain subpackages (subdirectories). Each subdirectory also needs, at least, an empty __init__.py file.

In the statement

					
>>> import a.b

				

the module named a.b designates a submodule named b inside a package called a.

When you import a package, its subpackages aren't imported all together. You need to explicitly say that in the __init__.py file.

It would be similar to saving the following line in the __init__.py file of your package:

					
import subpackage1, subpackage2, subpackage3
			
				

Remember that to locate modules and packages, Python uses the paths that are stored at sys.path. This variable is a simple list, like any other, and you can add any directory to this list that you want. Type sys.path at the prompt of your interpreter to know the current contents of this variable.

A new feature incorporated to release 2.0 is the possibility to rename modules when importing them. The syntax for that can be either

					
import module as newname
			
				

or

					
from module import name as newname
			
				

This feature is equivalent to the code

					
import module
newmodule = module
del module
			
				

Built-In Methods

All these built-in functions are part of the __builtin__ module, and you can use them after you have a module or package named m.

						
>>> m.__dict__            # lists the module dictionary
>>> m.x = m.__dict__["x"]   # provides access to a specific attribute
>>> m.__doc__            # returns the documentation string
>>> m.__name__            # returns the name of the module
>>> m.__file__            # returns the file name
>>> m.__path__            # returns the fully qualified package name

					

from in Contrast to import

The import and from statements allow one module to refer to objects from another module's namespace. They help eliminate problems with different modules that have some internal names equal. The next examples discuss the possible ways to use these statements.

						
>>> import string
>>> print string.join(list)

					

The previous example imports the string module as a local reference to an external module, allowing fully qualified references to any other objects in the string namespace.

The next example adds the join() function to the namespace of the current module. This method allows you to control exactly which names you import into your local namespace from a module.

						
>>> from string import join
>>> print join(list)

					

Now, take a look at the next line:

						
>>> from string import *

					

The problem with this syntax is that if the string module defines its own dosomething() function, you lose the dosomething() that might exist in your current namespace.

If you instead do a simple import string, you will keep your current dosomething() function. However, the dosomething() function from the string module will now be accessed by string.dosomething().

Tip

The main reason that you don't want to do from <module> import * is to avoid namespace clashing.



Also, let me tell you that identifiers beginning with _ (one underscore), such as _salary, aren't imported by a from <module> import * clause.

						
>>> import package1.string
>>> print package1.string.join(list)

					

The previous example loads the module string from the package package1.

						
>>> from package1 import string
>>> print string.join(list)

					

In order to access the string module, you need to reference its objects by typing string.<object>. This is the recommended notation to import a module from a package.

						
>>> from package1.string import join
>>> print join(list)
				
					

In the syntax form <package.module> import <object>, the <object> can be a subpackage of the package, a function, a class, a variable, and so on.

						
>>> from package1 import *

					

If you just say from package import *, it isn't guaranteed that all modules will be import unless you insert the following piece of code in the __init__.py file of the package.

						
__all__ = ["module1","module2","module3"]  

					

This is a list containing the names of the package modules that should be imported:

						
>>> from package.subpackage.module import *

					

Whenever you use a structure like package.subpackage.module, Python ensures that the package's __init__.py is loaded first. Afterwards, the subpackage's __init__.py is loaded, and only after they have been imported will the module finally be imported. After a package is loaded, there is no difference between a package and a module. Module objects represent both of them.

Releasing and Reloading Modules

After you have imported a module, you can release it from the system memory at anytime you want. The following example is to give you an idea of what I am talking about:

						
import string, sys
    lst = ["a","b","c","d"]
    print string.join(lst,"-")
del string
del sys.modules["string"]

					

Note that you also need to delete the module's reference, which exists in the sys.module variable.

The command reload <module> reloads and re-executes a module. Note that objects created before the reloading will use the previous version until they are re-created. Try to avoid using this command.

You can easily find out what the imported modules are by typing

						
>>> sys.modules.key()
['os.path', 'operator', 'os', 'exceptions', '__main__', 'ntpath',
'strop', 'nt', 'sys', '__builtin__', 'site', 'signal', UserDict',
'string', 'stat', 'cmath']
				
					


Last updated on 1/30/2002
Python Developer's Handbook, © 2002 Sams Publishing

< BACKMake Note | BookmarkCONTINUE >

Index terms contained in this section

.py extension
commands
      reload module
creating
      global namespaces, modules
directories
      packages
dosomething() function 2nd
extensions
      .py
finding
      contents of modules
foldersÓ
      Ò
from statement 2nd 3rd
functions
      dosomething() 2nd
      join()
global namespaces
      importing and creating, modules
import statement 2nd 3rd
importing
      global namespaces, modules
     modules
            syntax to rename
      modules from packages 2nd
join() function
modules 2nd 3rd 4th
     renaming
            syntax
      string
namespaces
     global
            importing and creating, modules
      string
packages 2nd 3rd 4th
reload module command
renaming
     modules
            syntax
searching
      contents of modules
statements
      from 2nd 3rd
      import 2nd 3rd
string module
string namespace
syntax
      importing and creating global namespaces, modules
     modulles
            renaming

© 2002, O'Reilly & Associates, Inc.