NumPy Style

Let's start concrete examples. Here, a sample Python file numpy_style.py is stored under the examples directory relative to the mkdocs.yml directory, so we would configure mkdocs.yml like below. In addition, we add an extension and extra javascript for Arithmatex.

plugins:
  - search
  - mkapi:
      src_dirs: [examples]

markdown_extensions:
  - pymdownx.arithmatex

extra_javascript:  # for pymdownx.arithmatex
  - https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_CHTML

Function

The numpy_style module defines a simple function add().

Code 5 numpy_style.add()

def add(x: int, y: int = 1) -> int:
    """Returns $x + y$.

    Parameters
    ----------
    x
        The first parameter.
    y
        The second parameter. Default={default}.

    Returns
    -------
    int
        Added value.

        !!! note
            The return type must be duplicated in the docstring to comply with the NumPy
            docstring style.

    Examples
    --------
    Examples should be written in doctest format.

    >>> add(1, 2)
    3

    Note
    ----
        MkApi doesn't check an underline that follows a section heading.
        Just skip one line.
    """
    return x + y

Then, write a tag anywhere in your Markdown source:

![mkapi](numpy_style.add)

MkApi generates the API documentation for the add() function.

function
numpy_style.add(x, y=1)

Returns x + y.

Parameters
  • x (int) The first parameter.
  • y (int, optional) The second parameter. Default=1.
Returns (int)

Added value.

Note

The return type must be duplicated in the docstring to comply with the NumPy docstring style.

Examples

Examples should be written in doctest format.

>>> add(1, 2)
3

Note

MkApi doesn't check an underline that follows a section heading. Just skip one line.

Note

In the above example, green dashed border lines are just guide for the eye to show the region of the documentation generated by MkApi for convenience.

In this simple example, you can see some features of MkApi.

  • Use of type annotation for both Parameters and Returns sections.
  • Add optional if parameters have default values.
  • Default value replacement by the {default} keyword in the Parameters section.
  • External hyperlink.
  • Use of MkDocs extensions: MathJax rendering and admonition.

Generator

The numpy_style module also defines a simple generator gen().

Code 6 numpy_style.gen()

def gen(n) -> Iterator[str]:
    """Yields a numbered string.

    Parameters
    ----------
    n : int
        The length of iteration.

    Yields
    ------
    str
        A numbered string.
    """
    for x in range(n):
        yield f"a{x}"

Then,

![mkapi](numpy_style.gen)

creates the documentation for the gen() generator.

generator
numpy_style.gen(n)

Yields a numbered string.

Parameters
  • n (int) The length of iteration.
Yields (str)

A numbered string.

In this simple example, note that:

  • Type inspection of gen() (generator prefix is added before google_style.gen).
  • The parameter n has no type annotation but you can specify it in the Parameters section directly.
  • Yields type is not "iterator of str" but "str", because the gen() is a generator.

Class

The numpy_style module also defines a simple class ExampleClass.

Code 7 numpy_style.ExampleClass

class ExampleClass:
    """A normal class.

    Parameters
    ----------
    x
        The first parameter.
    y
        The second parameter.

    Raises
    ------
    ValueError
        If the length of `x` is equal to 0.
    """

    def __init__(self, x: List[int], y: Tuple[str, int]):
        if len(x) == 0:
            raise ValueError()
        self.a: str = "abc"  #: The first attribute. Comment *inline* with attribute.
        #: The second attribute. Comment *before* attribute.
        self.b: Dict[str, int] = {"a": 1}
        self.c = None
        """int, optional: The third attribute. Docstring *after* attribute.

        Multiple paragraphs are supported."""
        self.d = 100  # Not attribute description because ':' is missing.

    def message(self, n: int) -> List[str]:
        """Returns a message list.

        Parameters
        ----------
        n
            Repetition.
        """
        return [self.a] * n

    @property
    def readonly_property(self):
        """str: Read-only property documentation."""
        return "readonly property"

    @property
    def readwrite_property(self) -> List[int]:
        """Read-write property documentation."""
        return [1, 2, 3]

    @readwrite_property.setter
    def readwrite_property(self, value):
        """Docstring in setter is ignored."""

As usual,

![mkapi](numpy_style.ExampleClass)

creates the documentation for the ExampleClass class.

class
numpy_style.ExampleClass(x, y)

A normal class.

Parameters
  • x (list of int) The first parameter.
  • y (str, int) The second parameter.
Attributes
  • a (str) The first attribute. Comment inline with attribute.
  • b (dict(str: int)) The second attribute. Comment before attribute.
  • c (int, optional) The third attribute. Docstring after attribute.
    Multiple paragraphs are supported.
  • readonly_property (str) Read-only property documentation.
  • readwrite_property (list of int) Read-write property documentation.
Raises
  • ValueError If the length of x is equal to 0.
Methods
  • message(n) (list of str) Returns a message list.
method
message(n) → list of str

Returns a message list.

Parameters
  • n (int) Repetition.

In this example, note that:

  • Type annotation using typing package (List and Tuple in this case) is converted into readable style.
  • Attributes section is inserted with type and description. These information is collected from the source code.
  • If callable objects have neither Returns nor Yields, the type appears on the object signature line like type annotation.
  • Properties are moved to the Attributes section with [RO] or [RW] prefix that indicates whether the property is read-only or read-write.
  • Methods section is newly created that displays a list of methods defined in this class. Note that it has a hyperlink to the object.

Note

Although you can write the docstring for a class in the __init__() function, the attribute inspection only works when you write it as a class level docstring.

Method

You can select a method of class (or any other object that can have docstring) to generate the documentation.

![mkapi](numpy_style.ExampleClass.message)

creates the documentation for the message() of ExampleClass class.

method
message(n) → list of str

Returns a message list.

Parameters
  • n (int) Repetition.

Data Class

The numpy_style module also defines a simple data class ExampleDataClass.

Code 8 numpy_style.ExampleDataClass

@dataclass
class ExampleDataClass:
    """A dataclass.

    Parameters
    ----------
    x
        The first parameter.

    Attributes
    ----------
    x
        The first attribute.
    y
        The second attribute.
    """

    x: int = 0
    y: int = field(default=1, init=False)

Then,

![mkapi](numpy_style.ExampleDataClass)

creates the documentation for the ExampleDataClass class.

dataclass
numpy_style.ExampleDataClass(x=0)

A dataclass.

Parameters
  • x (int, optional) The first parameter.
Attributes
  • x (int) The first attribute.
  • y (int) The second attribute.

In this example, note that:

  • A dataclass prefix instead of a class prefix.
  • Attributes type inspection as well as parameters if they are data class fields.

Heading Mode

The other mode to create documentation is heading. For example,

## ![mkapi](numpy_style.ExampleClass)

create a <h2> tag for the google_style.ExampleClass.

class

numpy_style.ExampleClass(x, y)

A normal class.

Parameters
  • x (list of int) The first parameter.
  • y (str, int) The second parameter.
Attributes
  • a (str) The first attribute. Comment inline with attribute.
  • b (dict(str: int)) The second attribute. Comment before attribute.
  • c (int, optional) The third attribute. Docstring after attribute.
    Multiple paragraphs are supported.
  • readonly_property (str) Read-only property documentation.
  • readwrite_property (list of int) Read-write property documentation.
Raises
  • ValueError If the length of x is equal to 0.
Methods
  • message(n) (list of str) Returns a message list.
method

message(n) → list of str

Returns a message list.

Parameters
  • n (int) Repetition.

Note that an ExampleClass item in nav menu is created.