Next / Previous / Contents / TCC Help System / NM Tech homepage

9.4. Build your own modules

If you have a common problem to solve, chances are very good that there are modules already written that will reduce the amount of code you have to write.

You can also build your own modules. A module is similar to a script (see Section 7, “How to write a self-executing Python script”): it is basically a text file containing the definitions of Python functions and variables.

To build your own module, use a common text editor to create a file with a name of the form “moduleName.py”. The moduleName you choose must be a valid Python name—it must start with a letter or underbar, and consist entirely of letters, underbars, and digits.

Inside that file, place Python function definitions and ordinary assignment statements.

Here is a very simple module containing one function and one variable. It lives in a file named cuber.py.

def cube(x):
    return x**3

cubeVersion = "1.9.33"

Here is an example interactive session that uses that module:

>>> dir()
['__builtins__', '__doc__', '__name__']
>>> from cuber import *
>>> dir()
['__builtins__', '__doc__', '__name__', 'cube', 'cubeVersion']
>>> cube(3)
27
>>> cubeVersion
'1.9.33'
>>> 

There is one more refinement we suggest for documenting the contents of a module. If the first line of the module's file is a string constant, it is saved as the module's “documentation string.” If you later import such a module using the form “import moduleName”, you can retrieve the contents of the documentation string using the expression “moduleName.__doc__”.

Here is an expanded version of our cuber.py with a documentation string:

"""cuber.py:  Simple homemade Python module

  Contents:
    cube(x):  Returns the cube of x
    cubeVersion:  Current version number of this module
"""
def cube(x):
    return x**3

cubeVersion = "1.9.33"

Finally, an example of how to retrieve the documentation string:

>>> import cuber
>>> print cuber.__doc__
cuber.py:  Simple homemade Python module

  Contents:
    cube(x):  Returns the cube of x
    cubeVersion:  Current version number of this module

>>> cuber.cube(10)
1000
>>>