Skip to content

plugin.py

This module contains the "mkdocstrings" plugin for MkDocs.

The plugin instantiates a Markdown extension (MkdocstringsExtension), and adds it to the list of Markdown extensions used by mkdocs during the on_config event hook.

Once the documentation is built, the on_post_build event hook is triggered and calls the handlers.teardown() method. This method is used to teardown the handlers that were instantiated during documentation buildup.

Finally, when serving the documentation, it can add directories to watch during the on_serve event hook.

RENDERING_OPTS_KEY: str ¤

The name of the rendering parameter in YAML configuration blocks.

SELECTION_OPTS_KEY: str ¤

The name of the selection parameter in YAML configuration blocks.

MkdocstringsPlugin ¤

An mkdocs plugin.

This plugin defines the following event hooks:

  • on_config
  • on_env
  • on_post_build
  • on_serve

Check the Developing Plugins page of mkdocs for more information about its plugin system.

config_scheme: Tuple[Tuple[str, mkdocs.config.config_options.Type]] ¤

The configuration options of mkdocstrings, written in mkdocs.yml.

Available options are:

  • watch: A list of directories to watch. Only used when serving the documentation with mkdocs. Whenever a file changes in one of directories, the whole documentation is built again, and the browser refreshed.
  • default_handler: The default handler to use. The value is the name of the handler module. Default is "python".
  • handlers: Global configuration of handlers. You can set global configuration per handler, applied everywhere, but overridable in each "autodoc" instruction. Example:
plugins:
  - mkdocstrings:
      handlers:
        python:
          selection:
            selection_opt: true
          rendering:
            rendering_opt: "value"
          setup_commands:
            - "import os"
            - "import django"
            - "os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_djang_app.settings')"
            - "django.setup()"
        rust:
          selection:
            selection_opt: 2

handlers: Handlers property readonly ¤

Get the instance of mkdocstrings.handlers.base.Handlers for this plugin/build.

Exceptions:

Type Description
RuntimeError

If the plugin hasn't been initialized with a config.

Returns:

Type Description
Handlers

An instance of mkdocstrings.handlers.base.Handlers (the same throughout the build).

inventory_enabled: bool property readonly ¤

Tell if the inventory is enabled or not.

Returns:

Type Description
bool

Whether the inventory is enabled.

__init__(self) special ¤

Initialize the object.

Source code in mkdocstrings/plugin.py
def __init__(self) -> None:
    """Initialize the object."""
    super().__init__()
    self._handlers: Optional[Handlers] = None

get_handler(self, handler_name) ¤

Get a handler by its name. See mkdocstrings.handlers.base.Handlers.get_handler.

Parameters:

Name Type Description Default
handler_name str

The name of the handler.

required

Returns:

Type Description
BaseHandler

An instance of a subclass of BaseHandler.

Source code in mkdocstrings/plugin.py
def get_handler(self, handler_name: str) -> BaseHandler:
    """Get a handler by its name. See [mkdocstrings.handlers.base.Handlers.get_handler][].

    Arguments:
        handler_name: The name of the handler.

    Returns:
        An instance of a subclass of [`BaseHandler`][mkdocstrings.handlers.base.BaseHandler].
    """
    return self.handlers.get_handler(handler_name)

on_config(self, config, **kwargs) ¤

Instantiate our Markdown extension.

Hook for the on_config event. In this hook, we instantiate our MkdocstringsExtension and add it to the list of Markdown extensions used by mkdocs.

We pass this plugin's configuration dictionary to the extension when instantiating it (it will need it later when processing markdown to get handlers and their global configurations).

Parameters:

Name Type Description Default
config Config

The MkDocs config object.

required
kwargs

Additional arguments passed by MkDocs.

{}

Returns:

Type Description
Config

The modified config.

Source code in mkdocstrings/plugin.py
def on_config(self, config: Config, **kwargs) -> Config:  # noqa: W0613 (unused arguments)
    """Instantiate our Markdown extension.

    Hook for the [`on_config` event](https://www.mkdocs.org/user-guide/plugins/#on_config).
    In this hook, we instantiate our [`MkdocstringsExtension`][mkdocstrings.extension.MkdocstringsExtension]
    and add it to the list of Markdown extensions used by `mkdocs`.

    We pass this plugin's configuration dictionary to the extension when instantiating it (it will need it
    later when processing markdown to get handlers and their global configurations).

    Arguments:
        config: The MkDocs config object.
        kwargs: Additional arguments passed by MkDocs.

    Returns:
        The modified config.
    """
    log.debug("Adding extension to the list")

    theme_name = None
    if config["theme"].name is None:
        theme_name = os.path.dirname(config["theme"].dirs[0])
    else:
        theme_name = config["theme"].name

    to_import: InventoryImportType = []
    for handler_name, conf in self.config["handlers"].items():
        for import_item in conf.pop("import", ()):
            if isinstance(import_item, str):
                import_item = {"url": import_item}
            to_import.append((handler_name, import_item))

    extension_config = {
        "site_name": config["site_name"],
        "theme_name": theme_name,
        "mdx": config["markdown_extensions"],
        "mdx_configs": config["mdx_configs"],
        "mkdocstrings": self.config,
    }
    self._handlers = Handlers(extension_config)

    try:  # noqa: WPS229
        # If autorefs plugin is explicitly enabled, just use it.
        autorefs = config["plugins"]["autorefs"]
        log.debug(f"Picked up existing autorefs instance {autorefs!r}")
    except KeyError:
        # Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
        autorefs = AutorefsPlugin()
        autorefs.scan_toc = False
        config["plugins"]["autorefs"] = autorefs
        log.debug(f"Added a subdued autorefs instance {autorefs!r}")
    # Add collector-based fallback in either case.
    autorefs.get_fallback_anchor = self.handlers.get_anchor

    mkdocstrings_extension = MkdocstringsExtension(extension_config, self.handlers, autorefs)
    config["markdown_extensions"].append(mkdocstrings_extension)

    config["extra_css"].insert(0, self.css_filename)  # So that it has lower priority than user files.

    self._inv_futures = []
    if to_import:
        inv_loader = futures.ThreadPoolExecutor(4)
        for handler_name, import_item in to_import:  # noqa: WPS440
            future = inv_loader.submit(
                self._load_inventory, self.get_handler(handler_name).load_inventory, **import_item
            )
            self._inv_futures.append(future)
        inv_loader.shutdown(wait=False)

    return config

on_env(self, env, config, **kwargs) ¤

Extra actions that need to happen after all Markdown rendering and before HTML rendering.

Hook for the on_env event.

  • Write mkdocstrings' extra files into the site dir.
  • Gather results from background inventory download tasks.
Source code in mkdocstrings/plugin.py
def on_env(self, env, config: Config, **kwargs):
    """Extra actions that need to happen after all Markdown rendering and before HTML rendering.

    Hook for the [`on_env` event](https://www.mkdocs.org/user-guide/plugins/#on_env).

    - Write mkdocstrings' extra files into the site dir.
    - Gather results from background inventory download tasks.
    """
    if self._handlers:
        css_content = "\n".join(handler.renderer.extra_css for handler in self.handlers.seen_handlers)
        write_file(css_content.encode("utf-8"), os.path.join(config["site_dir"], self.css_filename))

        if self.inventory_enabled:
            log.debug("Creating inventory file objects.inv")
            inv_contents = self.handlers.inventory.format_sphinx()
            write_file(inv_contents, os.path.join(config["site_dir"], "objects.inv"))

    if self._inv_futures:
        log.debug(f"Waiting for {len(self._inv_futures)} inventory download(s)")
        futures.wait(self._inv_futures, timeout=30)
        for page, identifier in collections.ChainMap(*(fut.result() for fut in self._inv_futures)).items():
            config["plugins"]["autorefs"].register_url(page, identifier)
        self._inv_futures = []

on_post_build(self, config, **kwargs) ¤

Teardown the handlers.

Hook for the on_post_build event. This hook is used to teardown all the handlers that were instantiated and cached during documentation buildup.

For example, the Python handler's collector opens a subprocess in the background and keeps it open to feed it the "autodoc" instructions and get back JSON data. Therefore, it must close it at some point, and it does it in its teardown() method which is indirectly called by this hook.

Parameters:

Name Type Description Default
config Config

The MkDocs config object.

required
kwargs

Additional arguments passed by MkDocs.

{}
Source code in mkdocstrings/plugin.py
def on_post_build(self, config: Config, **kwargs) -> None:  # noqa: W0613,R0201 (unused arguments, cannot be static)
    """Teardown the handlers.

    Hook for the [`on_post_build` event](https://www.mkdocs.org/user-guide/plugins/#on_post_build).
    This hook is used to teardown all the handlers that were instantiated and cached during documentation buildup.

    For example, the [Python handler's collector][mkdocstrings.handlers.python.PythonCollector] opens a subprocess
    in the background and keeps it open to feed it the "autodoc" instructions and get back JSON data. Therefore,
    it must close it at some point, and it does it in its
    [`teardown()` method][mkdocstrings.handlers.python.PythonCollector.teardown] which is indirectly called by
    this hook.

    Arguments:
        config: The MkDocs config object.
        kwargs: Additional arguments passed by MkDocs.
    """
    for future in self._inv_futures:
        future.cancel()

    if self._handlers:
        log.debug("Tearing handlers down")
        self.handlers.teardown()

on_serve(self, server, builder, **kwargs) ¤

Watch directories.

Hook for the on_serve event. In this hook, we add the directories specified in the plugin's configuration to the list of directories watched by mkdocs. Whenever a change occurs in one of these directories, the documentation is built again and the site reloaded.

Parameters:

Name Type Description Default
server

The livereload server instance.

required
builder Callable

The function to build the site.

required
kwargs

Additional arguments passed by MkDocs.

{}
Source code in mkdocstrings/plugin.py
def on_serve(self, server, builder: Callable, **kwargs):  # noqa: W0613 (unused arguments)
    """Watch directories.

    Hook for the [`on_serve` event](https://www.mkdocs.org/user-guide/plugins/#on_serve).
    In this hook, we add the directories specified in the plugin's configuration to the list of directories
    watched by `mkdocs`. Whenever a change occurs in one of these directories, the documentation is built again
    and the site reloaded.

    Arguments:
        server: The `livereload` server instance.
        builder: The function to build the site.
        kwargs: Additional arguments passed by MkDocs.
    """
    for element in self.config["watch"]:
        log.debug(f"Adding directory '{element}' to watcher")
        server.watch(element, builder)
Back to top