Skip to content

plugin ¤

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.

Classes:

Functions:

  • list_to_tuple

    Decorater to convert lists to tuples in the arguments.

MkdocstringsPlugin ¤

MkdocstringsPlugin()

Bases: BasePlugin[PluginConfig]

An mkdocs plugin.

This plugin defines the following event hooks:

  • on_config
  • on_env
  • on_post_build

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

Methods:

Attributes:

Source code in src/mkdocstrings/plugin.py
118
119
120
121
def __init__(self) -> None:
    """Initialize the object."""
    super().__init__()
    self._handlers: Handlers | None = None

handlers property ¤

handlers: Handlers

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

Raises:

  • RuntimeError

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

Returns:

inventory_enabled property ¤

inventory_enabled: bool

Tell if the inventory is enabled or not.

Returns:

  • bool

    Whether the inventory is enabled.

plugin_enabled property ¤

plugin_enabled: bool

Tell if the plugin is enabled or not.

Returns:

  • bool

    Whether the plugin is enabled.

get_handler ¤

get_handler(handler_name: str) -> BaseHandler

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

Parameters:

  • handler_name ¤

    (str) –

    The name of the handler.

Returns:

Source code in src/mkdocstrings/plugin.py
294
295
296
297
298
299
300
301
302
303
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 ¤

on_config(config: MkDocsConfig) -> MkDocsConfig | None

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:

  • config ¤

    (MkDocsConfig) –

    The MkDocs config object.

Returns:

  • MkDocsConfig | None

    The modified config.

Source code in src/mkdocstrings/plugin.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def on_config(self, config: MkDocsConfig) -> MkDocsConfig | None:
    """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.

    Returns:
        The modified config.
    """
    if not self.plugin_enabled:
        log.debug("Plugin is not enabled. Skipping.")
        return config
    log.debug("Adding extension to the list")

    theme_name = config.theme.name or os.path.dirname(config.theme.dirs[0])

    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}  # noqa: PLW2901
            to_import.append((handler_name, import_item))

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

    autorefs: AutorefsPlugin
    try:
        # If autorefs plugin is explicitly enabled, just use it.
        autorefs = config.plugins["autorefs"]  # type: ignore[assignment]
        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_anchors

    mkdocstrings_extension = MkdocstringsExtension(extension_config, self.handlers, autorefs)
    config.markdown_extensions.append(mkdocstrings_extension)  # type: ignore[arg-type]

    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:
            loader = self.get_handler(handler_name).load_inventory
            future = inv_loader.submit(
                self._load_inventory,  # type: ignore[misc]
                loader,
                **import_item,
            )
            self._inv_futures[future] = (loader, import_item)
        inv_loader.shutdown(wait=False)

    return config

on_env ¤

on_env(
    env: Environment,
    config: MkDocsConfig,
    *args: Any,
    **kwargs: Any,
) -> None

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 src/mkdocstrings/plugin.py
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def on_env(self, env: Environment, config: MkDocsConfig, *args: Any, **kwargs: Any) -> None:  # noqa: ARG002
    """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 not self.plugin_enabled:
        return
    if self._handlers:
        css_content = "\n".join(handler.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)
        results = {}
        # Reversed order so that pages from first futures take precedence:
        for fut in reversed(list(self._inv_futures)):
            try:
                results.update(fut.result())
            except Exception as error:  # noqa: BLE001
                loader, import_item = self._inv_futures[fut]
                loader_name = loader.__func__.__qualname__
                log.error(f"Couldn't load inventory {import_item} through {loader_name}: {error}")  # noqa: TRY400
        for page, identifier in results.items():
            config.plugins["autorefs"].register_url(page, identifier)  # type: ignore[attr-defined]
        self._inv_futures = {}

on_post_build ¤

on_post_build(config: MkDocsConfig, **kwargs: Any) -> None

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, a handler could open a subprocess in the background and keep it open to feed it "autodoc" instructions and get back JSON data. If so, it should then close the subprocess at some point: the proper place to do this is in the handler's teardown method, which is indirectly called by this hook.

Parameters:

  • config ¤

    (MkDocsConfig) –

    The MkDocs config object.

  • **kwargs ¤

    (Any, default: {} ) –

    Additional arguments passed by MkDocs.

Source code in src/mkdocstrings/plugin.py
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
def on_post_build(
    self,
    config: MkDocsConfig,  # noqa: ARG002
    **kwargs: Any,  # noqa: ARG002
) -> None:
    """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, a handler could open a subprocess in the background and keep it open
    to feed it "autodoc" instructions and get back JSON data. If so, it should then close the subprocess at some point:
    the proper place to do this is in the handler's `teardown` method, which is indirectly called by this hook.

    Arguments:
        config: The MkDocs config object.
        **kwargs: Additional arguments passed by MkDocs.
    """
    if not self.plugin_enabled:
        return

    for future in self._inv_futures:
        future.cancel()

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

PluginConfig ¤

Bases: Config

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

Attributes:

  • custom_templates

    Location of custom templates to use when rendering API objects.

  • default_handler

    The default handler to use. The value is the name of the handler module. Default is "python".

  • enable_inventory

    Whether to enable object inventory creation.

  • enabled

    Whether to enable the plugin. Default is true. If false, mkdocstrings will not collect or render anything.

  • handlers

    Global configuration of handlers.

custom_templates class-attribute instance-attribute ¤

custom_templates = Optional(Dir(exists=True))

Location of custom templates to use when rendering API objects.

Value should be the path of a directory relative to the MkDocs configuration file.

default_handler class-attribute instance-attribute ¤

default_handler = Type(str, default='python')

The default handler to use. The value is the name of the handler module. Default is "python".

enable_inventory class-attribute instance-attribute ¤

enable_inventory = Optional(Type(bool))

Whether to enable object inventory creation.

enabled class-attribute instance-attribute ¤

enabled = Type(bool, default=True)

Whether to enable the plugin. Default is true. If false, mkdocstrings will not collect or render anything.

handlers class-attribute instance-attribute ¤

handlers = Type(dict, default={})

Global configuration of handlers.

You can set global configuration per handler, applied everywhere, but overridable in each "autodoc" instruction. Example:

plugins:
  - mkdocstrings:
      handlers:
        python:
          options:
            option1: true
            option2: "value"
        rust:
          options:
            option9: 2

list_to_tuple ¤

list_to_tuple(
    function: Callable[P, R]
) -> Callable[P, R]

Decorater to convert lists to tuples in the arguments.

Source code in src/mkdocstrings/plugin.py
54
55
56
57
58
59
60
61
62
63
def list_to_tuple(function: Callable[P, R]) -> Callable[P, R]:
    """Decorater to convert lists to tuples in the arguments."""

    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        safe_args = [tuple(item) if isinstance(item, list) else item for item in args]
        if kwargs:
            kwargs = {key: tuple(value) if isinstance(value, list) else value for key, value in kwargs.items()}  # type: ignore[assignment]
        return function(*safe_args, **kwargs)  # type: ignore[arg-type]

    return wrapper