DOCUMENTING YOUR CODE - Complete Guide For Python Programming (2015)

Complete Guide For Python Programming (2015)

DOCUMENTING YOUR CODE

To document a Python object, docstring is used. A docstring is simply a triple-quoted sentence which gives a brief summary of the object. The object can be anything a function, a method, a class, etc.

Anything written in the triple quotes is the function’s docstring, which documents what the function does. A docstring, is the first thing that is defined in a function. Docstring is available at runtime as an attribute of the function. The docstring of a script should be usable as its ‘usage’ message, printed when the script is invoked with incorrect or missing arguments. The docstring is a phrase ending in a period. It describes the function’s effect as a command.

In docstring for a module classes, exceptions and functions that are exported by the module are listed. The docstring for a function or method summarize its behavior and document its arguments, return value(s), side effects and exceptions raised. The docstring for a class summarize its behavior and list the public methods and instance variables. Individual methods should be documented by their own docstring.

You can add a docstring to a function, class, or module by adding a string as the first indented statement.

For example:

#!/usr/bin/env python

# docstringexample.py

"""Example of using documentation strings."""

class Knight:

"""

An example class.

Call spam to get bacon.

"""

def spam(eggs="bacon"):

"""Prints the argument given."""

print(eggs)