Function documentation

If you’re using functions, they should form the bulk of your code, and as such, they should be documented properly. When documenting your functions, be sure to answer the following questions:

Documentation formatting

We recommend documenting your functions where the functions themselves are defined with specific comment syntax, and then using a utility to convert those notes into a standardized documentation format.

For the special comment syntax, we recommend following the numpydoc style of docstrings for Python and the roxygen2 format for R. Although these tools are meant primarily for package development, we recommend you use these formats whether or not you think you will eventually turn your code into a package. Not only will you be using a standard, commonly understood formats to document function inputs, outputs, etc., but if you do choose to turn your code into a package down the line, you can make use of automated documentation tools without having to go back and re-write old documentation.

Examples

Here is an example of the roxygen2 documentation format:

#' Add together two numbers
#'
#' @param x A number.
#' @param y A number, defaults to 2.
#' @return A number.
#' @examples
#' add(1, 1)
#' add(10, 1)

add <- function(x, y = 2) {
  x + y
}

Here is an example of the numpydoc docstrings format:

def add(x,y):
    """Add together two numbers.

    Parameters
    ----------
    x : num
        A number.
    y : num
        A number, defaults to 2.

    Returns
    ----------
    num
        A number with the sum of x and y.

    Examples
    ----------
    >>> add(1,1)
    """
    return x + y

Recommendations and resources

Language Recommended documentation format Associated automatic documentation tool Tutorial
R roxygen2 format roxygen2 Writing function documentation using roxygen2
Python numpydoc docstring standard sphynx Writing documentation for python packages