Python documentation¶

  • code comments
  • type hints
  • documentation strings

Code comments¶

Wherever in the code, one can insert one-line comments starting with the character #.

In [1]:
def powers(x,ps):
    result = []
    # for each value "p" in the "ps" collection,
    # I computes "x**p" and store it into "result"
    for p in ps:
        result.append(x**p)
    return result

Type hints¶

Type hinting was added to Python 3.5 and is an additional form to help the readers of your code. Some tools, such as PyCharm, are able to parse this information and help you edit your code.

In [2]:
def powers(x:float, ps:list) -> list:
    result = []
    # for each value "p" in the "ps" collection,
    # I computes "x**p" and store it into "result"
    for p in ps:
        result.append(x**p)
    return result

Documentation strings (docstrings)¶

The first string at the beginning of a python element (function, class, module...), will be kept as the __doc__ attribute of the element, and recognized as the documentation of the element. We call this a "docstring", as described in PEP 257.

In [3]:
def powers(x:float, ps:list) -> list:
    """Raise x to each value given in the ps collection."""
    result = []
    # for each value "p" in the "ps" collection,
    # I computes "x**p" and store it into "result"
    for p in ps:
        result.append(x**p)
    return result
In [4]:
print(powers.__doc__)
Raise x to each value given in the ps collection.

The built-in help() function displays the docstrings.

In [5]:
help(powers)
Help on function powers in module __main__:

powers(x: float, ps: list) -> list
    Raise x to each value given in the ps collection.

One can also use detailed multi-line strings, following a formatting style. Below, an example using the NumPy/SciPy style.

In [6]:
%%writefile mypowers.py
def powers(x:float, ps:list) -> list:
    """
    Raise a value to a collection of powers.

    Parameters
    ----------
    x : float
        the value to be raised.
    ps : list of float
        the collection of powers.

    Returns
    -------
    list of float
        collection of `x` raised to each value from `ps`.

    """

    result = []
    # for each value "p" in the "ps" collection,
    # I computes "x**p" and append it to "result"
    for p in ps:
        result.append(x**p)
    return result
Writing mypowers.py

From this, tools such as PDoc3 or Sphinx can generated RAW or HTML pages:

In [7]:
!pdoc mypowers.py
/bin/sh: 1: pdoc: not found

Questions ?¶

See also:

  • RealPython