Python Docstrings

Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docsting is defined by including a string constant as the first statement in the object's definition. For example, the following function defines a docstring:

def x_intercept(m, b):
    """
    Return the x intercept of the line y=m*x+b.  The x intercept of a
    line is the point at which it crosses the x axis (y=0).
    """
    return -b/m

Docstrings can be accessed from the interpreter and from Python programs using the "__doc__" attribute:

>>> print x_intercept.__doc__
    Return the x intercept of the line y=m*x+b.  The x intercept of a
    line is the point at which it crosses the x axis (y=0).

The pydoc module, which became part of the standard library in Python 2.1, can be used to display information about a Python object, including its docstring:

>>> from pydoc import help

>>> help(x_intercept)
Help on function x_intercept in module __main__:

x_intercept(m, b)
    Return the x intercept of the line y=m*x+b.  The x intercept of a
    line is the point at which it crosses the x axis (y=0).

For more information about Python docstrings, see the Python Tutorial or the Oreilly Network article Python Documentation Tips and Tricks.