6 Modules and Namespaces

There are different ways of loading modules (the Python equivalent of libraries.) How you load them affects how you use them, and there are some important details to remember. For example one may load the standard string module by

>>> import string
>>> x = 'my test string'
>>> print string.capitalize(x)
MY TEST STRING

If you are testing a module you have written and have changed it, importing the revised module a second time, even from within a completely different program, has no effect (Python notices that it has already been imported and doesn't bother to read and execute it again). To reload a module that was already imported, type:

>>> reload(mmm)

where mmm (with no quotation marks) is the name of your Python module that you wish to reload.

You can import using an alternate form:

>>> from string import *
>>> print capitalize(s)

Note that with this form of import, you do not prepend the module name to the function name, which makes using the capitalize function a bit more convenient. But this approach does have drawbacks. All the string module names appear in the user namespace. Importing many modules this way greatly increases the possibility of name collisions. If you import a module you are developing and want to reload an edited version, importing this way makes it very difficult to reload (it's possible, but usually too tedious to be worthwhile). So, when debugging Python modules or scripts interactively, don't use from mmm import *!

A better way to use the from ... import ... form of the import statement is to specify explicitly which names you want to import:

>>> from string import capitalize
>>> print capitalize(s)

This avoids cluttering your namespace with functions and variables that you do not use. Namespaces in general are a large and important topic in Python but are mainly beyond the scope of this quick overview. They are ubiquitous - there are namespaces associated with functions, modules, and class instances, and each such object has a local and a global namespace.

Questions or comments? Contact help@stsci.edu
Documented updated on 2002 May 3