Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Modules | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137104026065050119086242034

### Modules

As your programs grow in size, you’ll probably want to break them into multiple files for easier maintenance. To do this, Python allows you to put definitions in a file and use them as a module that can be imported into other programs and scripts. To create a module, put the relevant statements and definitions into a file that has the same name as the module. (Note: The file must have a .py suffix.) For example:

    # file : div.py
    def divide(a,b):
        q = a/b        # If a and b are integers, q is an integer
        r = a - q*b
        return (q,r)

To use your module in other programs, you can use the `import` statement:

    import div
    a, b = div.divide(2305, 29)

`import` creates a new namespace that contains all the objects defined in the module. To access this namespace, simply use the name of the module as a prefix, as in `div.divide()` in the preceding example.

If you want to import a module using a different name, supply the `import` statement with an optional `as` qualifier as follows:

    import div as foo
    a,b = foo.divide(2305,29)

To import specific definitions into the current namespace, use the `from` statement:

    from div import divide
    a,b = divide(2305,29)       # No longer need the div prefix

To load all of a module’s contents into the current namespace, you can also use the following:

    from div import *

Finally, the `dir()` function lists the contents of a module and is a useful tool for interactive experimentation, since it can be used to provide a list of available functions and variables:

    >>> import string
    >>> dir(string)
    ['_ _builtins_ _', '_ _doc_ _', '_ _file_ _', '_ _name_ _', '_idmap',
     '_idmapL', '_lower', '_swapcase', '_upper', 'atof', 'atof_error',
     'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize',
     'capwords', 'center', 'count', 'digits', 'expandtabs', 'find',
    ...
    >>>

| 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.