Writing API details in RST markup

One of the benefits of using the RST markup is that we can provide formal API documentation. The API parameters and return values are formatted using an RST field list. Generally, a field list has the following form:

:field1: some value 
:field2: another value 

A field list is a sequence of field labels (as :label:) and a value associated with that label. The label is generally short, and the value can be as long as needed. Field lists are also used to provide parameters to directives.

We'll use an extended form of the RST field list syntax to write the API documentation. We'll extend the field name to become a multipart item. We'll add prefixes with keywords such as param or type. The prefix will be followed by the parameter's name.

There are several field prefixes. We can use any of these: param, parameter, arg, argument, key, and keyword. For example, we might write the following code:

:param rank: Numeric rank of the card 
:param suit: Suit of the card 

We generally use param (or parameter) for the positional parameters, and key (or keyword) for the keyword parameters. These field list definitions will be collected in an indented section. The Sphinx tool will also compare the names in the documentation with the names in the function argument list, to be sure that they match.

We can also define the type of a parameter using type as a prefix:

:type rank: integer in the range 1-13. 

While this can be helpful, it's far better to use proper type hints in the function and method definitions. The type hints are used by Sphinx and other tools. They are checked by mypy, also.

For functions that return a value, we should describe the result. We can summarize the return value with the field label of returns or return

:returns: soft total for this card

Additionally, we should also include information about exceptions that are unique to this function. We have four aliases for this field: raises, raise, except, and exception. We would write the following code:

:raises TypeError: rank value not in range(1, 14). 

We can also describe the attributes of a class. For this, we can use var, ivar, or cvar. We might write the following code:

:ivar soft: soft points for this card; usually hard points, except for aces. 
:ivar hard: hard points for this card; usually the rank, except for face cards. 

We should use ivar for instance variables, and cvar for class variables. However, there's no visible difference in the final HTML output.

These field list constructs are used to prepare docstrings for classes, class methods, and standalone functions. We'll look at each case in the later section.

Now, let's see how to write class and method function docstrings.

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

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