Linux/Unix > Python Essential Reference, Second Edition > 8. Modules and Packages > Modules | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238111161105087128011106194131013

### Modules

You can turn any valid source file into a module by loading it with the `import` statement. For example, consider the following code:

    # file : spam.py
    a = 37                    # A variable
    def foo:                  # A function
        print "I'm foo"
    class bar:                # A class
        def grok(self):
            print "I'm bar.grok"
    b = bar()                 # Create an instance

To load this code as a module, you use the statement `import spam`. The first time `import` is used to load a module, it does three things:

1. It creates a new namespace that serves as a namespace to all the objects defined in the corresponding source file. This is the namespace accessed when functions and methods defined within the module use the `global` statement.

2. It executes the code contained in the module within the newly created namespace.

3. It creates a name within the caller that refers to the module namespace. This name matches the name of the module and is used as follows:

       import spam           # Loads and executes the module 'spam'
       print spam.a          # Accesses a member of module 'spam'
       spam.foo()
       c = spam.bar()
       ...

To import multiple modules, supply `import` with a comma-separated list of module names, like this:

    import socket, os, regex

Modules can be imported using alternative names by using the `as` qualifier. For example:

    import os as system
    import socket as net, thread as threads
    system.chdir("..")
    net.gethostname()

Use the `from` statement to load specific definitions within a module into the current namespace. The `from` statement is identical to `import` except that instead of creating a name referring to the newly created module namespace, references to one or more of the objects defined in the module are placed into the current namespace:

    from socket import gethostname
                                   # Put gethostname in current namespace

    print gethostname()            # Use without module name
    socket.gethostname()           # NameError: socket

The `from` statement also accepts a comma-separated list of object names. The asterisk (`*`) wildcard character can also be used to load all the definitions in a module except those that start with an underscore. For example:

    from socket import gethostname, socket
    from socket import *   # Load all definitions into current namespace

Modules can more precisely control the set of names that are imported by `from` `module` `import *` by defining a list `_ _all_ _`. For example:

    # module: foo.py
    _ _all_ _ = [ 'bar', 'spam' ]     # Names to be imported by *

In addition, the `as` qualifier can be used to rename specific objects imported with `from`. For example:

    from socket import gethostname as hostname
    h = hostname()

The `import` statement can appear at any point in a program. However, the code in each module is loaded and executed only once, regardless of how often you use the `import` statement. Subsequent `import` statements simply create a reference to the module namespace created on a previous import. You can find a dictionary containing all currently loaded modules in the variable `sys.modules`, which is a dictionary that maps module names to module objects. The contents of this dictionary are used to determine whether `import` loads a fresh copy of a module.

The `from` `module` `import *` statement can only be used at the top level of a module. In particular, it’s illegal to use this form of `import` inside function bodies, due to the way in which it interacts with function scoping rules.

Each module defines a variable `_ _name_ _` that contains the module name. Programs can examine this variable to determine the module in which they’re executing. The top-level module of the interpreter is named `_ _main_ _`. Programs specified on the command line or entered interactively run inside the `_ _main_ _` module. Sometimes, a program may alter its behavior, depending on whether it has been imported as a module or is running in `_ _main_ _`. This can be done as follows:

    # Check if running as a program
    if _ _name_ _ == '_ _main_ _':
          # Yes
          statements
    else:
          # No, I must have been imported as a module
          statements

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.