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.
Python comes with a large collection of built-in modules. See the Python Library Reference.
The python.org site also hosts a
collection of thousands of third-party modules: see
the Python package index.
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 “”. The moduleName.py you choose must be a
valid Python name—it must start with a letter or
underbar, and consist entirely of letters, underbars, and
digits.
moduleName
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 ”, you can retrieve the contents of the
documentation string using the expression “moduleName”.
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
>>>