How to produce documentation for Python functions?


Documentation is an important aspect of writing code, especially when it comes to functions. It helps others understand what the function does, how to use it, and what parameters it takes. Python has a built-in documentation tool called docstrings. A docstring is a string that appears as the first statement in a function and provides documentation about the function.

Information about a function or documentation is put in docstrings in a function. The following are the guidelines to be followed while writing the docstrings.

The first line should always be a short, concise summary of the object’s purpose. For brevity, it should not explicitly state the object’s name or type.  This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description

Sphinx

Sphinx is the most popular Python documentation tool. It converts reStructuredText markup language into a range of output formats including HTML, LaTeX (for printable PDF versions), manual pages, and plain text.

When run, Sphinx will import your code and using Python’s introspection features it will extract all function, method and class signatures. It will also extract the accompanying docstrings, and compile it all into well-structured and easily readable documentation for your project.

Example: Simple function with docstring

In this example, we have defined a function called greet which takes a parameter called name. The first statement in the function is a docstring which describes what the function does. The docstring is enclosed in triple quotes.

To access the docstring of a function, you can use the built-in help() function.

The help() function displays the docstring of the function.

def greet(name):
    """
    This function greets the person passed in as a parameter.
    """
    print("Hello, " + name + ". How are you doing?")

# call the function
greet("John")
help(greet)

Output

Hello, John. How are you doing?
Help on function greet in module __main__:
greet(name)
This function greets the person passed in as a parameter.

Example: Function with detailed docstring

In this example, we have defined a function called calculate_sum which takes a parameter called numbers. The docstring of the function provides more detailed information about the function, including the type of parameter it takes, and the type of value it returns.

Again, we can use the help() function to access the docstring of the function:

def calculate_sum(numbers):
    """
    This function calculates the sum of a list of numbers.
    
    Parameters:
    numbers (list): A list of numbers to be summed.
    
    Returns:
    int: The sum of the list of numbers.
    """
    total = 0
    for num in numbers:
        total += num
    return total

# call the function
print(calculate_sum([1, 2, 3, 4, 5]))
help(calculate_sum)

Output

15
Help on function calculate_sum in module __main__:
calculate_sum(numbers)
This function calculates the sum of a list of numbers.
Parameters:
numbers (list): A list of numbers to be summed.
Returns:
int: The sum of the list of numbers.

Using docstrings is a great way to provide documentation for your functions. It makes it easier for others to understand your code and use your functions correctly.

Documenting your code is an important practice that can save time and effort for both you and other developers who may work on your code. Proper documentation helps you understand your own code later and makes it easier for others to use your code. Here are some tips on how to document your Python functions -

Example

The easiest way to document a Python function is by using docstrings. A docstring is a string literal that appears as the first statement in a module, function, class, or method definition. It can be accessed using the `__doc__` attribute of the object. Here's an example of a function with a docstring:

In this example, the docstring provides information on what the function does, what arguments it expects, and what it returns. You can access the docstring by running `help(add_numbers)` or `add_numbers.__doc__`.

def add_numbers(a, b):
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b
print(add_numbers.__doc__)

Output

Adds two numbers together.
   :param a: The first number.
   :param b: The second number.
   :return: The sum of a and b.

Example: Use Type Annotations

Type annotations can also be used to document the expected types of function arguments and the return value. Type annotations are optional and do not affect the function's behavior, but they can improve code readability and help prevent bugs. Here's an example:

In this example, the type annotations indicate that both arguments should be integers, and the function should return an integer. You can access the type annotations by running `add_numbers.__annotations__`.

def add_numbers(a:int, b:int) -> int:
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b
print(add_numbers.__annotations__)

Output

{'a': , 'b': , 'return': }

Example: Use a Documentation Generator

While docstrings and type annotations are useful, they can be time-consuming to write and maintain. A documentation generator can automatically generate documentation for your code based on these annotations. Popular documentation generators for Python include Sphinx and pydoc.

Sphinx is a popular documentation generator that is used for Python and other programming languages. It can generate documentation in various formats such as HTML, PDF, and EPUB. Sphinx uses a markup language called reStructuredText, which is similar to Markdown.

Pydoc is a built-in documentation generator that comes with Python. It generates documentation based on docstrings and can be run from the command line or used as a module.

Here's an example of Sphinx documentation generated from the docstring of the `add_numbers` function:

def add_numbers(a:int, b:int) -> int:
    """
    Adds two numbers together.
    :param a: The first number.
    :param b: The second number.
    :return: The sum of a and b.
    """
    return a + b

With the above function defined in a Python module, you can use Sphinx to generate documentation for it by adding the following reStructuredText markup to a .rst file.The :members: option tells Sphinx to generate documentation for all functions and classes in the module.

.. autofunction:: add_numbers
    :members:

Once you've added the above markup to your .rst file, you can generate the documentation using the sphinx-build command:

sphinx-build -b html source_dir build_dir 

This will generate HTML documentation for your Python module, including the add_numbers function. The resulting documentation will include the function signature, docstring, and any other relevant information that you've included in your markup.

Output

add_numbers(a, b)
    Adds two numbers together.

    :param a: The first number.
    :param b: The second number.
    :type a: int
    :type b: int
    :return: The sum of a and b.
    :rtype: int

Example: Sphinx documentation generator

Sphinx is a documentation generator that is commonly used for documenting Python projects. It allows you to write documentation in plain text using reStructuredText markup and generates HTML, PDF, and other formats from your source code. Here's an example of how to document a Python function using Sphinx:

First, you'll need to install Sphinx:

!pip install sphinx

Then, create a new directory for your Sphinx documentation and initialize it with the following command:

sphinx-quickstart

Follow the prompts to configure your Sphinx project. When prompted to provide a path for your documentation root, enter the path to the directory containing your Python code.

Once your project is set up, you can write documentation for your Python functions using reStructuredText markup.

Here's an example -

def greet(name: str) -> str:
    """
    Return a greeting for the given name.
    
    :param name: The name to greet.
    :return: A string greeting.
    """
    return f"Hello, {name}!"

In the docstring for the `greet` function, we provide a description of what the function does and its parameters. We use reStructuredText markup to format the docstring.

After you've written your documentation, you can generate the documentation in HTML format using the following command:

make html

The generated documentation will be located in the `_build/html` directory.

Example: Pydoc documentation generator

Pydoc is a built-in Python tool for generating documentation from Python modules. It generates HTML documentation from docstrings in your code. Here's an example of how to use Pydoc:

First, we'll write a Python module with a function that we want to document:

# mymodule.py

def greet(name):
    """
    Return a greeting for the given name.
    
    :param name: The name to greet.
    :return: A string greeting.
    """
    return f"Hello, {name}!"

Next, we can use Pydoc to generate documentation for our module. To generate HTML documentation, run the following command in your terminal -

python -m pydoc -w mymodule

This will generate a file called `mymodule.html` in your current directory. You can open the HTML file in your web browser to view the documentation.

Pydoc can also generate documentation in other formats, such as plain text or man pages. To generate plain text documentation, run the following command:

python -m pydoc mymodule

This will print the documentation to the terminal.

Updated on: 19-May-2023

171 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements