Skip to content

Python handler¤

Handler options¤

Like every handler, the Python handler accepts the common selection and rendering options, both as global and local options. The selection options gives you control over the selection of Python objects, while the rendering options lets you change how the documentation is rendered.

It also accepts these additional global-only options:

Option Type Description Default
setup_commands list of str Run these commands before starting the documentation collection. []

Example: setup Django before collecting documentation

# mkdocs.yml
plugins:
  - mkdocstrings:
      handlers:
        python:
          setup_commands:
            - import os
            - import django
            - os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_django_app.settings")
            - django.setup()

Important

Additional options like setup_commands are used only once, when instantiating the handler the first time it is requested. This is why they are considered global-only options, as they will have no effect if used as local options.

Selection¤

The following options are directly passed to the handler's collector. See Collector: pytkdocs to learn more about pytkdocs.

Option Type Description Default
filters list of str List of filtering regular expressions. Prefix with ! to exclude objects whose name match. The default means exclude private members. ["!^_[^_]"]
members bool, or list of str Explicitly select members. True means all, false means none. True
inherited_members bool Also select members inherited from parent classes. False
docstring_style str Docstring style to parse. pytkdocs supports google, numpy and restructured-text. Note: Numpy-style requires the numpy-style extra of pytkdocs. "google"
docstring_options dict Options to pass to the docstring parser. See Collector: pytkdocs {}
new_path_syntax bool Whether to use the new "colon" path syntax when importing objects. False

Configuration example

# mkdocs.yml
plugins:
  - mkdocstrings:
      handlers:
        python:
          selection:
            filters:
              - "!^_"  # exlude all members starting with _
              - "^__init__$"  # but always include __init__ modules and methods
::: my_package
    selection:
      filters: []  # pick up everything

Rendering¤

The default rendering options.

Option Type Description Default
show_root_heading bool Show the heading of the object at the root of the documentation tree. False
show_root_toc_entry bool If the root heading is not shown, at least add a ToC entry for it. True
show_root_full_path bool Show the full Python path for the root object heading. True
show_object_full_path bool Show the full Python path of every object. False
show_root_members_full_path bool Show the full Python path of objects that are children of the root object (for example, classes in a module). When False, show_object_full_path overrides. False
show_category_heading bool When grouped by categories, show a heading for each category. False
show_if_no_docstring bool Show the object heading even if it has no docstring or children with docstrings. False
show_signature_annotations bool Show the type annotations in methods and functions signatures. False
show_source bool Show the source code of this object. True
show_bases bool Show the base classes of a class. True
group_by_category bool Group the object's children by categories: attributes, classes, functions, methods, and modules. True
heading_level int The initial heading level to use. 2
members_order str The members ordering to use. Options: alphabetical - order by the members names, source - order members as they appear in the source file. alphabetical

These options affect how the documentation is rendered.

Configuration example

# mkdocs.yml
plugins:
  - mkdocstrings:
      handlers:
        python:
          rendering:
            show_root_heading: yes
## `ClassA`

::: my_package.my_module.ClassA
    rendering:
      show_root_heading: no
      heading_level: 3

Collector: pytkdocs¤

The tool used by the Python handler to collect documentation from Python source code is pytkdocs. It stands for (Python) Take Docs, and is supposed to be a pun on MkDocs (Make Docs?).

Supported docstrings styles¤

Right now, pytkdocs supports the Google-style, Numpy-style and reStructuredText-style docstring formats. The style used by default is the Google-style. You can configure what style you want to use with the docstring_style and docstring_options selection options, both globally or per autodoc instruction.

Google-style¤

You can see examples of Google-style docstrings in Napoleon's documentation.

Sections¤

Docstrings sections are parsed by pytkdocs and rendered by mkdocstrings. Supported sections are:

  • Arguments (or Args, Parameters, Params)
  • Attributes
  • Examples (or Example)
  • Raises (or Raise, Except, Exceptions)
  • Returns (or Return)
Admonitions¤

Additionally, any section that is not recognized will be transformed into its admonition equivalent. For example:

"""
Note: You can disable this behavior with the `replace_admonitions` option.
    To prevent `pytkdocs` from converting sections to admonitions,
    use the `replace_admonitions`:

    ```md
    ::: my_package.my_module
        selection:
          docstring_style: google  # this is the default
          docstring_options:
            replace_admonitions: no 
    ```

    So meta!
"""
"""
!!! note "You can disable this behavior with the `replace_admonitions` option."
    To prevent `pytkdocs` from converting sections to admonitions,
    use the `replace_admonitions`:

    ```md
    ::: my_package.my_module
        selection:
          docstring_style: google  # this is the default
          docstring_options:
            replace_admonitions: no 
    ```

    So meta!
"""

You can disable this behavior with the replace_admonitions parser option.

To prevent pytkdocs from converting sections to admonitions, use the replace_admonitions parser option:

::: my_package.my_module
    selection:
      docstring_style: google  # this is the default
      docstring_options:
        replace_admonitions: no 

So meta!

As shown in the above example, this can be disabled with the replace_admonitions option of the Google-style parser:

::: my_package.my_module
    selection:
      docstring_style: google  # this is the default
      docstring_options:
        replace_admonitions: no 
Annotations¤

Type annotations are read both in the code and in the docstrings.

Example with a function

Expand the source at the end to see the original code!

A short description of this function.

Parameters:

Name Type Description Default
param1 int

An integer?

required
param2 Optional[str]

A string? If you have a long description, you can split it on multiple lines. Just remember to indent those lines consistently.

Complex markup is supported in sections items.

I'm a code block!
None
Source code in snippets/function_annotations_google.py
def my_function(param1: int, param2: Optional[str] = None) -> str:
    """A short description of this function.

    Arguments:
        param1: An integer?
        param2: A string? If you have a long description,
            you can split it on multiple lines.
            Just remember to indent those lines consistently.

            Complex markup is supported in sections items.

                I'm a code block!
    """
    return f"{param2}{param1}"

Numpy-style¤

Extra dependency required

You'll need an extra dependency to parse Numpy-style docstrings:

pdm add -d --group docs 'pytkdocs[numpy-style]'
poetry add -D 'pytkdocs[numpy-style]'
pip install 'pytkdocs[numpy-style]'
# etc.

You can see examples of Numpy-style docstrings in numpydoc's documentation.

reStructuredText-style¤

Partial support

Only RST-style is supported, not the whole RST markup specification. Docstrings will still be converted as Markdown.

You can see examples of reStructuredText-style docstrings in Sphinx's documentation.

Sections¤

Docstrings directives are parsed by pytkdocs and rendered by mkdocstrings. Supported directives are:

  • param (or parameter, arg, argument, key, keyword)
  • type
  • raises (or raise, except, exception)
  • var (or ivar, cvar)
  • vartype
  • returns (or return1)
  • rtype

Details about how to use each directive can be found in the Sphinx domain documentation

Annotations¤

Type annotations are read both in the code and in the docstrings.

Example with a function

Expand the source at the end to see the original code!

A short description of this function.

Complex markup is supported in the main description section.

I'm a code block!

Parameters:

Name Type Description Default
param1 int

An integer?

required
param2 Optional[str]

A string? If you have a long description, you can split it on multiple lines.

None
Source code in snippets/function_annotations_rst.py
def my_function(param1: int, param2: Optional[str] = None) -> str:
    """A short description of this function.

    Complex markup is supported in the main description section.

        I'm a code block!

    :param param1: An integer?
    :param param2: A string? If you have a long description,
        you can split it on multiple lines.
    """
    return f"{param2}{param1}"

Finding modules¤

In order for pytkdocs to find your packages and modules, you should take advantage of the usual Python loading mechanisms:

  • install your package in the current virtualenv:

    . venv/bin/activate
    pip install -e .
    

    poetry install
    

    ...etc.

  • or add your package(s) parent directory in the PYTHONPATH.

(The following instructions assume your Python package is in the src directory.)

In Bash and other shells, you can run your command like this (note the prepended PYTHONPATH=...):

PYTHONPATH=src poetry run mkdocs serve

You could also export that variable, but this is not recommended as it could affect other Python processes:

export PYTHONPATH=src  # Linux/Bash and similar
setx PYTHONPATH src  # Windows, USE AT YOUR OWN RISKS

You can also use the Python handler setup_commands:

# mkdocs.yml
plugins:
  - mkdocstrings:
      handlers:
        python:
          setup_commands:
            - import sys
            - sys.path.append("src")
            # or sys.path.insert(0, "src")

Mocking libraries¤

You may want to to generate documentation for a package while its dependencies are not available. The Python handler provides itself no builtin way to mock libraries, but you can use the setup_commands to mock them manually:

mkdocs.yml

plugins:
  - mkdocstrings:
      handlers:
        python:
          setup_commands:
            - import sys
            - from unittest.mock import MagicMock as mock
            - sys.modules["lib1"] = mock()
            - sys.modules["lib2"] = mock()
            - sys.modules["lib2.module1"] = mock()
            - sys.modules["lib2.module1.moduleB"] = mock()
            # etc

Here are some CSS rules for the Material for MkDocs theme:

/* Indentation. */
div.doc-contents:not(.first) {
  padding-left: 25px;
  border-left: 4px solid rgba(230, 230, 230);
  margin-bottom: 80px;
}

Here are some CSS rules for the built-in ReadTheDocs theme:

/* Indentation. */
div.doc-contents:not(.first) {
  padding-left: 25px;
  border-left: 4px solid rgba(230, 230, 230);
  margin-bottom: 60px;
}
Back to top