Python Documentation Tools – Why is it Needed?

In this article, we’ll discuss various ways to implement Python documentation tools and techniques.

In programming, documentation is the particulars that report the program’s functionality to other programmers. A program’s documentation provides valuable insight into its uses to the programmer.

Despite how good a program is, poorly written documentation will prevent users from accessing its maximum potential. Let’s look at the various ways to document your python programs.

Using Comment lines as Python Documentation Tool

Generally, code comments describe a particular section of code to the reader. Code commenting allows developers to understand the purpose of the program’s design, functionality, or valuable information for testers. It is good practice to include comment lines under Python classes and functions. Overall, comment lines allow programmers to better understand a code’s purpose.

Let’s look at some examples that demonstrate code commenting.

Various languages use different syntax for comment lines. In Python, the hashtag/pound sign(#) is used for commenting.

def myFunction():
     # comments under function declaration describe its purpose
     # prints 'hello Python' in console
      print("hello Python")

According to PEP 8 guidelines, it is important that the maximum length of a comment line is 72 characters. Use additional comment lines for extra space.

Comment lines can provide the following information:

  • Code Intent – The intentions for a specific line of code.
# Recieve user input. If user input is invalid, ask for valid input
  • Tags – Tags allow us to label parts of code that require specific attention. Some common tags in programming include : TODO, FIXME, DEBUG
# TODO : Include parameter for user input
  • Planning Process – While implementing a new section to your code, comment lines can be a great way to sketch a basic outline to refer to. After implementation, remove such kinds of comment lines as they may confuse other readers.
# STEP 1 - Create a class 
# STEP 2 - Decide parameters for class
# STEP 3 - Create a function that generates an instance for the class

Using Docstrings as Python Documentation Tool

Documentation for a majority of Python programs revolves around docstrings. Docstrings are a form of built-in strings that allow programmers to create documentation for their work. To help users, Python has a function help() that displays docstrings to consoles. Refer to the following example:

 help(int)

Output

Help on class int in module builtins:

class int(object)
 |  int([x]) -> integer
 |  int(x, base=10) -> integer
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is a number, return x.__int__().  For floating point
 |  numbers, this truncates towards zero.
 |  
 |  If x is not a number or if base is given, then x must be a string,
 |  bytes, or bytearray instance representing an integer literal in the
 |  given base.  The literal can be preceded by '+' or '-' and be surrounded
 |  by whitespace.  The base defaults to 10.  Valid bases are 0 and 2-36.
 |  Base 0 means to interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |...
...
...

Creating Docstrings In Python

To create Docstrings in Python, we must use triple-double quotes regardless of multi-lines. A basic Docstring should contain a brief explanation of a program or a program component. Here’s an example of a simple docstring.

"""This is a basic single lined docstring in Python"""

Single-line docstrings are used to describe an object in summary, whereas multi-line docstrings depict a detailed explanation of the object. This is the format for a multi-lined docstring.

  • A single-line summary docstring
  • Blank line after the summary
  • A multi-lined explanation for the single-lined docstring
  • Blank line after the explanation

Note that the maximum number of characters for a docstring line is 72. Any further characters must be written in the next line.

Refer to the following example.

""" Basic single lined summary

Multilined explanation of the docstring. This part will contain a vast explanation that supports the single lined summary. Make sure to elaborated on every detail that has only to do with the particular code section. Include blank lines before and after writing the explanation.
"""

print("Code continuation...") 

Different Types of Docstrings in Python Documentation Tools

In Python, There are 3 types of Docstrings based on what they explain.

  • Python Modules/Packages Docstrings
  • Class Docstrings
  • Function Docstrings

Module Docstrings

A Python module’s docstring should contain the list of sub-modules used to create the package. The module Docstrings documents the entire module and its functions. A developer must include the following in the Module docstrings.

  • A short explanation of the package and its purpose for creation
  • An entire list of classes, methods, exceptions, or other objects within the module.
  • Each function of the module must contain the following
    • An explanation of the function and its use.
    • Existing keyword or non-keyword arguments.
    • All optional arguments must be labeled “optional”.
    • Upon failure to execute, exceptions that can arise.
    • If it affects the program as a whole upon calling.

Class Docstrings

All Classes must contain docstrings for their methods and the class itself. The docstrings can be found directly below the class declaration.

class MyClass:
    """Class docstring explaning the class"""

    def myMethod(self, name: str):
        """Method docstring explaining the method"""

        print(f'Hello {name}')

A Class’s docstring should contain the following information:

  • A short explanation of the class and its purpose
  • List of all the class methods with explanation
  • All class attributes/properties
  • Presence of any subclasses or parent classes

A Class’s methods should contain the following information:

  • A short explanation of the method and its purpose
  • List of keyword and non-keyword arguments
  • Denote arguments that are optional or have default values.
  • Mention if executing the method may affect the entire program’s behavior
  • Upon failure to execute, exceptions that can arise.

Function Docstrings

Function Docstrings are known as Script Docstrings. Docstrings for functions should be written at the top of the python file before the reader reads the actual code. Documentation for functions must be written thoroughly and clearly. Any third-party dependencies should be mentioned in the docstrings. Let’s refer to the following example

"""Example Function Script

The main purpose of the function or program should be mentioned in these first few lines. Make sure the explanation is straightforward and precise. 

Additional information for the program such as compatibility or accepted versions of Python can be mentioned here. 

Any third party dependencies shall be included.

Include the list of functions that the program contains.
"""
# Actual program

def myFunction():
     """Purpose of the function
         Parameters :
         Returns :
     """
       print("Actual Code")

def main():
     ...
     ...

Different Python Documentation Tools and Modules

Writing documentation for large programs can be time-consuming. Therefore, automated documentation modules can be a quick solution. Let’s look at the following list of tools.

Sphinx

Python Sphinx consists of various Python documentation tools to automate documentation in various formats.

Compatible file formats include:

  • HTML
  • LaTeX
  • ePub
  • Texinfo
  • Manual Pages
  • Plain Text

By default, Sphinx uses reStructuredText markup language. reStructuredText format is Python’s official documentation tools standard. For beginners, it may be difficult to read, but it explains most features. Sphinx provides extensive cross-references for functions, classes, citations, and inbuilt terms. It has automatic code highlighting with the help of Pygments highlighter.

Let’s see how we can start a Sphinx project:

Upon installation, a script called sphinx-quickstart sets up a source directory with the default configuration. Run the script using the following command

$ sphinx-quickstart

index.rst file created by sphinx-quickstart will have some content. The index content will be on the front page of your HTML document. Here is an example file:

Welcome to Python Pool !
===================================

**Python Pool** Welcome to Python Pool, your number one source for learning python. We’re dedicated to giving you the very best Python Learning Experience, with a focus on Effective Tutorials, Courses and *Info graphics*.

.. note::

     This document is written using reStructuredText

Epydoc

Epydoc allows us to create API documentation for our Python modules using docstrings. It makes use of the Epytext markup language used to format docstrings. It allows us to add information on specific sections of the program such as parameters or instance variables. Epydoc also supports the following formats:

  • reStructuredText (Python’s official format for documentation)
  • Javadoc
  • Plain Text

The latest version of Epydoc is Epydoc 3.0

Epydoc extracts API documentation for Python objects and writes in a selected format. Here are the command line commands:

epydoc [--html|--pdf] [-o DIR] [--parse-only|--introspect-only] [-v|-q]
       [--name NAME] [--url URL] [--docformat NAME] [--graph GRAPHTYPE]
       [--inheritance STYLE] [--config FILE] OBJECTS...

In order to write HTML documentation for your module, run the following command

$ epydoc --html yourModuleName -o yourModuleDocFile

Epydoc also provides a UI interface for OS systems where command line interfaces are not convenient.

Pycco

Pycco is a quick and efficient programming-based documentation generator. It views HTML text that displays comments and docstrings alongside your code file. The syntax highlighting is achieved using Pygments. Pycco is an open-source project and is available here. Manually install the module using the following command:

pip install pycco

or

git clone git://github.com/pycco-docs/pycco.git
cd pycco
python setup.py install

MkDocs

MkDocs is a simple Python documentation tool that builds project documentation using Markdown. All documentation is written using Markdown and configured using a YAML file.

These are the features of the MkDocs Python module:

  • There are various clean themes available for MkDocs. MkDocs support third-party themes or custom-made themes.
  • Along with themes, the project documentation can be easily customized using plugins. Markdown extensions provide multiple configuration options.
  • Host your builds under GitHub pages, Amazon s3, or any other platform.
  • Built-in servers provide a live preview of your documentation.

Install the module manually using the following command

pip install mkdocs

To create new documentation, run the following command.

mkdocs new exampleProject
cd exampleProject

Running the command will generate a YAML config folder and docs folder containing documentation source files. The source files are all written in Markdown.

After creating the project, run the mkdocs serve command. This will create a server and display the main page of your documentation.

$ mkdocs serve
INFO    -  Building documentation...
INFO    -  Cleaning site directory
[I 160402 15:50:43 server:271] Serving on http://127.0.0.1:8000
[I 160402 15:50:43 handlers:58] Start watching changes
[I 160402 15:50:43 handlers:60] Start detecting changes

FAQs

What is the best Python documentation tool?

Sphinx is a commonly used Python documentation tool. It uses Pythons recommended reStructedText markup language. It has various output formats (HTML, LaTeX, Manual Pages, and Plain Text)

What is documentation in Python programming?

Documentation provides users with an overview of the Python object. Python documentation is concise and maintained throughout the existence of the project. It allows new users to understand the purpose and how to use the Python object.

Conclusion

In this article, we have discussed Python Documentation Tools and the importance of documenting work done in Python. Python has features that help document within the source file. For large sections of code, writing documentation can be hectic. A simple solution is to use the following modules for automated documentation:

  • Sphinx
  • Epydoc
  • Pycco
  • MkDocs

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments