Writing effective docstrings

When writing docstrings, we need to focus on the essential information that our audience needs. When we look at using a library module, what do we need to know? Whatever questions we ask means that other programmers will often have similar questions. There are two boundaries that we should stay inside when we write docstrings:

  • It's best to avoid abstract overviews, high-level requirements, user stories, or background that is not tied directly to the code. We should provide the background in a separate document. A tool such as Sphinx can combine background material and code in a single document.
  • It's best to also avoid overly detailed how it works implementation trivia. The code is readily available, so there's no point in recapitulating the code in the documentation. If the code is too obscure, perhaps it should be rewritten to make it clearer.

Perhaps the single most important thing that developers want is a working example of how to use the Python object. The RST :: literal block is the backbone of these examples.

We'll often write RST code samples in the following manner:

Here's an example:: 
 
    d = Deck() 
    c = d.pop() 
 

The double colon, ::, precedes an indented block. The indented block is recognized by the RST parser as code and will be literally passed through to the final document.

In addition to an example, the formal API is also important. We'll take a look at several API definition techniques in the later section. These rely on the RST field list syntax. It's very simple, which makes it very flexible.

Once we're past the example and the API, there are a number of other things that compete for the third place. What else we need to write depends on the context. There appear to be three cases:

  • Files, including packages and modules: In these cases, we're providing an overview or introduction to a collection of modules, classes, or function definitions. We need to provide a simple roadmap or overview of the various elements in the file. In the case where the module is relatively small, we might provide the doctest and code samples at this level.
  • Classes, including method functions: This is where we often provide code samples and doctest blocks that explain the class API. Because a class may be stateful and may have a relatively complex API, we may need to provide rather lengthy documentation. Individual method functions will often have detailed documentation.
  • Functions: We may provide code samples and doctest blocks that explain the function. Because a function is often stateless, we may have a relatively simple API. In some cases, we may avoid more sophisticated RST markup and focus on the help() function's documentation.

We'll take a look at each of these broad, vague documentation contexts in some detail.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset