Skip to content

Docstrings

This page showcase the mkdocsstrings extension with its own code.

Todo

Make a dedicated demo package to have just what is needed to style


mkdocstrings.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.

Attributes:

InventoryImportType module-attribute

InventoryImportType = list[tuple[str, Mapping[str, Any]]]

InventoryLoaderType module-attribute

InventoryLoaderType = Callable[..., Iterable[tuple[str, str]]]

P module-attribute

P = ParamSpec('P')

R module-attribute

R = TypeVar('R')

log module-attribute

log = get_logger(__name__)

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 .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
def __init__(self) -> None:
    """Initialize the object."""
    super().__init__()
    self._handlers: Handlers | None = None

css_filename class-attribute instance-attribute

css_filename = 'assets/_mkdocstrings.css'

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 .venv/lib/python3.11/site-packages/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

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 .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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("Picked up existing autorefs instance %r", autorefs)
    except KeyError:
        # Otherwise, add a limited instance of it that acts only on what's added through `register_anchor`.
        autorefs = AutorefsPlugin()
        autorefs.config = AutorefsConfig()
        autorefs.scan_toc = False
        config.plugins["autorefs"] = autorefs
        log.debug("Added a subdued autorefs instance %r", autorefs)
    # 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 .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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("Waiting for %s inventory download(s)", len(self._inv_futures))
        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("Couldn't load inventory %s through %s: %s", import_item, 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 .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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 .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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

mkdocstrings.extension

This module holds the code of the Markdown extension responsible for matching "autodoc" instructions.

The extension is composed of a Markdown block processor that matches indented blocks starting with a line like identifier.

For each of these blocks, it uses a handler to collect documentation about the given identifier and render it with Jinja templates.

Both the collection and rendering process can be configured by adding YAML configuration under the "autodoc" instruction:

::: some.identifier
    handler: python
    options:
      option1: value1
      option2:
      - value2a
      - value2b
      option_x: etc

Classes:

Attributes:

log module-attribute

log = get_logger(__name__)

AutoDocProcessor

AutoDocProcessor(parser: BlockParser, md: Markdown, config: dict, handlers: Handlers, autorefs: AutorefsPlugin)

Bases: BlockProcessor

Our "autodoc" Markdown block processor.

It has a test method that tells if a block matches a criterion, and a run method that processes it.

It also has utility methods allowing to get handlers and their configuration easily, useful when processing a matched block.

Parameters:

  • parser

    (BlockParser) –

    A markdown.blockparser.BlockParser instance.

  • md

    (Markdown) –

    A markdown.Markdown instance.

  • config

    (dict) –

    The configuration of the mkdocstrings plugin.

  • handlers

    (Handlers) –

    The handlers container.

  • autorefs

    (AutorefsPlugin) –

    The autorefs plugin instance.

Methods:

  • run

    Run code on the matched blocks.

  • test

    Match our autodoc instructions.

Attributes:

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
def __init__(
    self,
    parser: BlockParser,
    md: Markdown,
    config: dict,
    handlers: Handlers,
    autorefs: AutorefsPlugin,
) -> None:
    """Initialize the object.

    Arguments:
        parser: A `markdown.blockparser.BlockParser` instance.
        md: A `markdown.Markdown` instance.
        config: The [configuration][mkdocstrings.plugin.PluginConfig] of the `mkdocstrings` plugin.
        handlers: The handlers container.
        autorefs: The autorefs plugin instance.
    """
    super().__init__(parser=parser)
    self.md = md
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs
    self._updated_envs: set = set()

md instance-attribute

md = md

regex class-attribute instance-attribute

regex = compile('^(?P<heading>#{1,6} *|)::: ?(?P<name>.+?) *$', flags=MULTILINE)

run

Run code on the matched blocks.

The identifier and configuration lines are retrieved from a matched block and used to collect and render an object.

Parameters:

  • parent

    (Element) –

    The parent element in the XML tree.

  • blocks

    (MutableSequence[str]) –

    The rest of the blocks to be processed.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
def run(self, parent: Element, blocks: MutableSequence[str]) -> None:
    """Run code on the matched blocks.

    The identifier and configuration lines are retrieved from a matched block
    and used to collect and render an object.

    Arguments:
        parent: The parent element in the XML tree.
        blocks: The rest of the blocks to be processed.
    """
    block = blocks.pop(0)
    match = self.regex.search(block)

    if match:
        if match.start() > 0:
            self.parser.parseBlocks(parent, [block[: match.start()]])
        # removes the first line
        block = block[match.end() :]

    block, the_rest = self.detab(block)

    if not block and blocks and blocks[0].startswith(("    handler:", "    options:")):
        # YAML options were separated from the `:::` line by a blank line.
        block = blocks.pop(0)

    if match:
        identifier = match["name"]
        heading_level = match["heading"].count("#")
        log.debug("Matched '::: %s'", identifier)

        html, handler, data = self._process_block(identifier, block, heading_level)
        el = Element("div", {"class": "mkdocstrings"})
        # The final HTML is inserted as opaque to subsequent processing, and only revealed at the end.
        el.text = self.md.htmlStash.store(html)
        # We need to duplicate the headings directly, just so 'toc' can pick them up,
        # otherwise they wouldn't appear in the final table of contents.
        # These headings are generated by the `BaseHandler.do_heading` method (Jinja filter),
        # which runs in the inner Markdown conversion layer, and not in the outer one where we are now.
        headings = handler.get_headings()
        el.extend(headings)
        # These duplicated headings will later be removed by our `_HeadingsPostProcessor` processor,
        # which runs right after 'toc' (see `MkdocstringsExtension.extendMarkdown`).

        page = self._autorefs.current_page
        if page is not None:
            for heading in headings:
                rendered_anchor = heading.attrib["id"]
                self._autorefs.register_anchor(page, rendered_anchor)

                if "data-role" in heading.attrib:
                    self._handlers.inventory.register(
                        name=rendered_anchor,
                        domain=handler.domain,
                        role=heading.attrib["data-role"],
                        priority=1,  # register with standard priority
                        uri=f"{page}#{rendered_anchor}",
                    )

                    # also register other anchors for this object in the inventory
                    try:
                        data_object = handler.collect(rendered_anchor, handler.fallback_config)
                    except CollectionError:
                        continue
                    for anchor in handler.get_anchors(data_object):
                        if anchor not in self._handlers.inventory:
                            self._handlers.inventory.register(
                                name=anchor,
                                domain=handler.domain,
                                role=heading.attrib["data-role"],
                                priority=2,  # register with lower priority
                                uri=f"{page}#{rendered_anchor}",
                            )

        parent.append(el)

    if the_rest:
        # This block contained unindented line(s) after the first indented
        # line. Insert these lines as the first block of the master blocks
        # list for future processing.
        blocks.insert(0, the_rest)

test

test(parent: Element, block: str) -> bool

Match our autodoc instructions.

Parameters:

  • parent

    (Element) –

    The parent element in the XML tree.

  • block

    (str) –

    The block to be tested.

Returns:

  • bool

    Whether this block should be processed or not.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
def test(self, parent: Element, block: str) -> bool:  # noqa: ARG002
    """Match our autodoc instructions.

    Arguments:
        parent: The parent element in the XML tree.
        block: The block to be tested.

    Returns:
        Whether this block should be processed or not.
    """
    return bool(self.regex.search(block))

MkdocstringsExtension

MkdocstringsExtension(config: dict, handlers: Handlers, autorefs: AutorefsPlugin, **kwargs: Any)

Bases: Extension

Our Markdown extension.

It cannot work outside of mkdocstrings.

Parameters:

  • config

    (dict) –

    The configuration items from mkdocs and mkdocstrings that must be passed to the block processor when instantiated in extendMarkdown.

  • handlers

    (Handlers) –

    The handlers container.

  • autorefs

    (AutorefsPlugin) –

    The autorefs plugin instance.

  • **kwargs

    (Any, default: {} ) –

    Keyword arguments used by markdown.extensions.Extension.

Methods:

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
def __init__(self, config: dict, handlers: Handlers, autorefs: AutorefsPlugin, **kwargs: Any) -> None:
    """Initialize the object.

    Arguments:
        config: The configuration items from `mkdocs` and `mkdocstrings` that must be passed to the block processor
            when instantiated in [`extendMarkdown`][mkdocstrings.extension.MkdocstringsExtension.extendMarkdown].
        handlers: The handlers container.
        autorefs: The autorefs plugin instance.
        **kwargs: Keyword arguments used by `markdown.extensions.Extension`.
    """
    super().__init__(**kwargs)
    self._config = config
    self._handlers = handlers
    self._autorefs = autorefs

extendMarkdown

extendMarkdown(md: Markdown) -> None

Register the extension.

Add an instance of our AutoDocProcessor to the Markdown parser.

Parameters:

  • md

    (Markdown) –

    A markdown.Markdown instance.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
def extendMarkdown(self, md: Markdown) -> None:  # noqa: N802 (casing: parent method's name)
    """Register the extension.

    Add an instance of our [`AutoDocProcessor`][mkdocstrings.extension.AutoDocProcessor] to the Markdown parser.

    Arguments:
        md: A `markdown.Markdown` instance.
    """
    md.parser.blockprocessors.register(
        AutoDocProcessor(md.parser, md, self._config, self._handlers, self._autorefs),
        "mkdocstrings",
        priority=75,  # Right before markdown.blockprocessors.HashHeaderProcessor
    )
    md.treeprocessors.register(
        _HeadingsPostProcessor(md),
        "mkdocstrings_post_headings",
        priority=4,  # Right after 'toc'.
    )
    md.treeprocessors.register(
        _TocLabelsTreeProcessor(md),
        "mkdocstrings_post_toc_labels",
        priority=4,  # Right after 'toc'.
    )

mkdocstrings.handlers.base

Base module for handlers.

This module contains the base classes for implementing handlers.

Classes:

Functions:

  • do_any

    Check if at least one of the item in the sequence evaluates to true.

Attributes:

CollectorItem module-attribute

CollectorItem = Any

BaseHandler

BaseHandler(handler: str, theme: str, custom_templates: str | None = None)

The base handler class.

Inherit from this class to implement a handler.

You will have to implement the collect and render methods. You can also implement the teardown method, and override the update_env method, to add more filters to the Jinja environment, making them available in your Jinja templates.

To define a fallback theme, add a fallback_theme class-variable. To add custom CSS, add an extra_css variable or create an 'style.css' file beside the templates.

If the given theme is not supported (it does not exist), it will look for a fallback_theme attribute in self to use as a fallback theme.

Parameters:

  • handler

    (str) –

    The name of the handler.

  • theme

    (str) –

    The name of theme to use.

  • custom_templates

    (str | None, default: None ) –

    Directory containing custom templates.

Methods:

  • collect

    Collect data given an identifier and user configuration.

  • do_convert_markdown

    Render Markdown text; for use inside templates.

  • do_heading

    Render an HTML heading and register it for the table of contents. For use inside templates.

  • get_anchors

    Return the possible identifiers (HTML anchors) for a collected item.

  • get_extended_templates_dirs

    Load template extensions for the given handler, return their templates directories.

  • get_headings

    Return and clear the headings gathered so far.

  • get_templates_dir

    Return the path to the handler's templates directory.

  • load_inventory

    Yield items and their URLs from an inventory file streamed from in_file.

  • render

    Render a template using provided data and configuration options.

  • teardown

    Teardown the handler.

  • update_env

    Update the Jinja environment.

Attributes:

  • domain (str) –

    The handler's domain, used to register objects in the inventory, for example "py".

  • enable_inventory (bool) –

    Whether the inventory creation is enabled.

  • env
  • extra_css

    Extra CSS.

  • fallback_config (dict) –

    Fallback configuration when searching anchors for identifiers.

  • fallback_theme (str) –

    Fallback theme to use when a template isn't found in the configured theme.

  • name (str) –

    The handler's name, for example "python".

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def __init__(self, handler: str, theme: str, custom_templates: str | None = None) -> None:
    """Initialize the object.

    If the given theme is not supported (it does not exist), it will look for a `fallback_theme` attribute
    in `self` to use as a fallback theme.

    Arguments:
        handler: The name of the handler.
        theme: The name of theme to use.
        custom_templates: Directory containing custom templates.
    """
    paths = []

    # add selected theme templates
    themes_dir = self.get_templates_dir(handler)
    paths.append(themes_dir / theme)

    # add extended theme templates
    extended_templates_dirs = self.get_extended_templates_dirs(handler)
    for templates_dir in extended_templates_dirs:
        paths.append(templates_dir / theme)

    # add fallback theme templates
    if self.fallback_theme and self.fallback_theme != theme:
        paths.append(themes_dir / self.fallback_theme)

        # add fallback theme of extended templates
        for templates_dir in extended_templates_dirs:
            paths.append(templates_dir / self.fallback_theme)

    for path in paths:
        css_path = path / "style.css"
        if css_path.is_file():
            self.extra_css += "\n" + css_path.read_text(encoding="utf-8")
            break

    if custom_templates is not None:
        paths.insert(0, Path(custom_templates) / handler / theme)

    self.env = Environment(
        autoescape=True,
        loader=FileSystemLoader(paths),
        auto_reload=False,  # Editing a template in the middle of a build is not useful.
    )
    self.env.filters["any"] = do_any
    self.env.globals["log"] = get_template_logger(self.name)

    self._headings: list[Element] = []
    self._md: Markdown = None  # type: ignore[assignment]  # To be populated in `update_env`.

domain class-attribute instance-attribute

domain: str = 'default'

The handler's domain, used to register objects in the inventory, for example "py".

enable_inventory class-attribute instance-attribute

enable_inventory: bool = False

Whether the inventory creation is enabled.

env instance-attribute

env = Environment(autoescape=True, loader=FileSystemLoader(paths), auto_reload=False)

extra_css class-attribute instance-attribute

extra_css = ''

Extra CSS.

fallback_config class-attribute

fallback_config: dict = {}

Fallback configuration when searching anchors for identifiers.

fallback_theme class-attribute instance-attribute

fallback_theme: str = ''

Fallback theme to use when a template isn't found in the configured theme.

name class-attribute instance-attribute

name: str = ''

The handler's name, for example "python".

collect

Collect data given an identifier and user configuration.

In the implementation, you typically call a subprocess that returns JSON, and load that JSON again into a Python dictionary for example, though the implementation is completely free.

Parameters:

  • identifier

    (str) –

    An identifier for which to collect data. For example, in Python, it would be 'mkdocstrings.handlers' to collect documentation about the handlers module. It can be anything that you can feed to the tool of your choice.

  • config

    (MutableMapping[str, Any]) –

    The handler's configuration options.

Returns:

  • CollectorItem

    Anything you want, as long as you can feed it to the handler's render method.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def collect(self, identifier: str, config: MutableMapping[str, Any]) -> CollectorItem:
    """Collect data given an identifier and user configuration.

    In the implementation, you typically call a subprocess that returns JSON, and load that JSON again into
    a Python dictionary for example, though the implementation is completely free.

    Arguments:
        identifier: An identifier for which to collect data. For example, in Python,
            it would be 'mkdocstrings.handlers' to collect documentation about the handlers module.
            It can be anything that you can feed to the tool of your choice.
        config: The handler's configuration options.

    Returns:
        Anything you want, as long as you can feed it to the handler's `render` method.
    """
    raise NotImplementedError

do_convert_markdown

do_convert_markdown(text: str, heading_level: int, html_id: str = '', *, strip_paragraph: bool = False, autoref_hook: AutorefsHookInterface | None = None) -> Markup

Render Markdown text; for use inside templates.

Parameters:

  • text

    (str) –

    The text to convert.

  • heading_level

    (int) –

    The base heading level to start all Markdown headings from.

  • html_id

    (str, default: '' ) –

    The HTML id of the element that's considered the parent of this element.

  • strip_paragraph

    (bool, default: False ) –

    Whether to exclude the

    tag from around the whole output.

Returns:

  • Markup

    An HTML string.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def do_convert_markdown(
    self,
    text: str,
    heading_level: int,
    html_id: str = "",
    *,
    strip_paragraph: bool = False,
    autoref_hook: AutorefsHookInterface | None = None,
) -> Markup:
    """Render Markdown text; for use inside templates.

    Arguments:
        text: The text to convert.
        heading_level: The base heading level to start all Markdown headings from.
        html_id: The HTML id of the element that's considered the parent of this element.
        strip_paragraph: Whether to exclude the <p> tag from around the whole output.

    Returns:
        An HTML string.
    """
    treeprocessors = self._md.treeprocessors
    treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = heading_level  # type: ignore[attr-defined]
    treeprocessors[IdPrependingTreeprocessor.name].id_prefix = html_id and html_id + "--"  # type: ignore[attr-defined]
    treeprocessors[ParagraphStrippingTreeprocessor.name].strip = strip_paragraph  # type: ignore[attr-defined]

    if autoref_hook:
        self._md.inlinePatterns[AutorefsInlineProcessor.name].hook = autoref_hook  # type: ignore[attr-defined]

    try:
        return Markup(self._md.convert(text))
    finally:
        treeprocessors[HeadingShiftingTreeprocessor.name].shift_by = 0  # type: ignore[attr-defined]
        treeprocessors[IdPrependingTreeprocessor.name].id_prefix = ""  # type: ignore[attr-defined]
        treeprocessors[ParagraphStrippingTreeprocessor.name].strip = False  # type: ignore[attr-defined]
        self._md.inlinePatterns[AutorefsInlineProcessor.name].hook = None  # type: ignore[attr-defined]
        self._md.reset()

do_heading

do_heading(content: Markup, heading_level: int, *, role: str | None = None, hidden: bool = False, toc_label: str | None = None, **attributes: str) -> Markup

Render an HTML heading and register it for the table of contents. For use inside templates.

Parameters:

  • content

    (Markup) –

    The HTML within the heading.

  • heading_level

    (int) –

    The level of heading (e.g. 3 -> h3).

  • role

    (str | None, default: None ) –

    An optional role for the object bound to this heading.

  • hidden

    (bool, default: False ) –

    If True, only register it for the table of contents, don't render anything.

  • toc_label

    (str | None, default: None ) –

    The title to use in the table of contents ('data-toc-label' attribute).

  • **attributes

    (str, default: {} ) –

    Any extra HTML attributes of the heading.

Returns:

  • Markup

    An HTML string.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def do_heading(
    self,
    content: Markup,
    heading_level: int,
    *,
    role: str | None = None,
    hidden: bool = False,
    toc_label: str | None = None,
    **attributes: str,
) -> Markup:
    """Render an HTML heading and register it for the table of contents. For use inside templates.

    Arguments:
        content: The HTML within the heading.
        heading_level: The level of heading (e.g. 3 -> `h3`).
        role: An optional role for the object bound to this heading.
        hidden: If True, only register it for the table of contents, don't render anything.
        toc_label: The title to use in the table of contents ('data-toc-label' attribute).
        **attributes: Any extra HTML attributes of the heading.

    Returns:
        An HTML string.
    """
    # Produce a heading element that will be used later, in `AutoDocProcessor.run`, to:
    # - register it in the ToC: right now we're in the inner Markdown conversion layer,
    #   so we have to bubble up the information to the outer Markdown conversion layer,
    #   for the ToC extension to pick it up.
    # - register it in autorefs: right now we don't know what page is being rendered,
    #   so we bubble up the information again to where autorefs knows the page,
    #   and can correctly register the heading anchor (id) to its full URL.
    # - register it in the objects inventory: same as for autorefs,
    #   we don't know the page here, or the handler (and its domain),
    #   so we bubble up the information to where the mkdocstrings extension knows that.
    el = Element(f"h{heading_level}", attributes)
    if toc_label is None:
        toc_label = content.unescape() if isinstance(content, Markup) else content
    el.set("data-toc-label", toc_label)
    if role:
        el.set("data-role", role)
    self._headings.append(el)

    if hidden:
        return Markup('<a id="{0}"></a>').format(attributes["id"])

    # Now produce the actual HTML to be rendered. The goal is to wrap the HTML content into a heading.
    # Start with a heading that has just attributes (no text), and add a placeholder into it.
    el = Element(f"h{heading_level}", attributes)
    el.append(Element("mkdocstrings-placeholder"))
    # Tell the inner 'toc' extension to make its additions if configured so.
    toc = cast(TocTreeprocessor, self._md.treeprocessors["toc"])
    if toc.use_anchors:
        toc.add_anchor(el, attributes["id"])
    if toc.use_permalinks:
        toc.add_permalink(el, attributes["id"])

    # The content we received is HTML, so it can't just be inserted into the tree. We had marked the middle
    # of the heading with a placeholder that can never occur (text can't directly contain angle brackets).
    # Now this HTML wrapper can be "filled" by replacing the placeholder.
    html_with_placeholder = tostring(el, encoding="unicode")
    assert (  # noqa: S101
        html_with_placeholder.count("<mkdocstrings-placeholder />") == 1
    ), f"Bug in mkdocstrings: failed to replace in {html_with_placeholder!r}"
    html = html_with_placeholder.replace("<mkdocstrings-placeholder />", content)
    return Markup(html)

get_anchors

get_anchors(data: CollectorItem) -> tuple[str, ...]

Return the possible identifiers (HTML anchors) for a collected item.

Parameters:

Returns:

  • tuple[str, ...]

    The HTML anchors (without '#'), or an empty tuple if this item doesn't have an anchor.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_anchors(self, data: CollectorItem) -> tuple[str, ...]:  # noqa: ARG002
    """Return the possible identifiers (HTML anchors) for a collected item.

    Arguments:
        data: The collected data.

    Returns:
        The HTML anchors (without '#'), or an empty tuple if this item doesn't have an anchor.
    """
    return ()

get_extended_templates_dirs

get_extended_templates_dirs(handler: str) -> list[Path]

Load template extensions for the given handler, return their templates directories.

Parameters:

  • handler

    (str) –

    The name of the handler to get the extended templates directory of.

Returns:

  • list[Path]

    The extensions templates directories.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_extended_templates_dirs(self, handler: str) -> list[Path]:
    """Load template extensions for the given handler, return their templates directories.

    Arguments:
        handler: The name of the handler to get the extended templates directory of.

    Returns:
        The extensions templates directories.
    """
    discovered_extensions = entry_points(group=f"mkdocstrings.{handler}.templates")
    return [extension.load()() for extension in discovered_extensions]

get_headings

get_headings() -> Sequence[Element]

Return and clear the headings gathered so far.

Returns:

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_headings(self) -> Sequence[Element]:
    """Return and clear the headings gathered so far.

    Returns:
        A list of HTML elements.
    """
    result = list(self._headings)
    self._headings.clear()
    return result

get_templates_dir

get_templates_dir(handler: str | None = None) -> Path

Return the path to the handler's templates directory.

Override to customize how the templates directory is found.

Parameters:

  • handler

    (str | None, default: None ) –

    The name of the handler to get the templates directory of.

Raises:

Returns:

  • Path

    The templates directory path.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_templates_dir(self, handler: str | None = None) -> Path:
    """Return the path to the handler's templates directory.

    Override to customize how the templates directory is found.

    Arguments:
        handler: The name of the handler to get the templates directory of.

    Raises:
        ModuleNotFoundError: When no such handler is installed.
        FileNotFoundError: When the templates directory cannot be found.

    Returns:
        The templates directory path.
    """
    handler = handler or self.name
    try:
        import mkdocstrings_handlers
    except ModuleNotFoundError as error:
        raise ModuleNotFoundError(f"Handler '{handler}' not found, is it installed?") from error

    for path in mkdocstrings_handlers.__path__:
        theme_path = Path(path, handler, "templates")
        if theme_path.exists():
            return theme_path

    raise FileNotFoundError(f"Can't find 'templates' folder for handler '{handler}'")

load_inventory classmethod

load_inventory(in_file: BinaryIO, url: str, base_url: str | None = None, **kwargs: Any) -> Iterator[tuple[str, str]]

Yield items and their URLs from an inventory file streamed from in_file.

Parameters:

  • in_file

    (BinaryIO) –

    The binary file-like object to read the inventory from.

  • url

    (str) –

    The URL that this file is being streamed from (used to guess base_url).

  • base_url

    (str | None, default: None ) –

    The URL that this inventory's sub-paths are relative to.

  • **kwargs

    (Any, default: {} ) –

    Ignore additional arguments passed from the config.

Yields:

  • tuple[str, str]

    Tuples of (item identifier, item URL).

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
@classmethod
def load_inventory(
    cls,
    in_file: BinaryIO,  # noqa: ARG003
    url: str,  # noqa: ARG003
    base_url: str | None = None,  # noqa: ARG003
    **kwargs: Any,  # noqa: ARG003
) -> Iterator[tuple[str, str]]:
    """Yield items and their URLs from an inventory file streamed from `in_file`.

    Arguments:
        in_file: The binary file-like object to read the inventory from.
        url: The URL that this file is being streamed from (used to guess `base_url`).
        base_url: The URL that this inventory's sub-paths are relative to.
        **kwargs: Ignore additional arguments passed from the config.

    Yields:
        Tuples of (item identifier, item URL).
    """
    yield from ()

render

Render a template using provided data and configuration options.

Parameters:

Returns:

  • str

    The rendered template as HTML.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def render(self, data: CollectorItem, config: Mapping[str, Any]) -> str:
    """Render a template using provided data and configuration options.

    Arguments:
        data: The collected data to render.
        config: The handler's configuration options.

    Returns:
        The rendered template as HTML.
    """
    raise NotImplementedError

teardown

teardown() -> None

Teardown the handler.

This method should be implemented to, for example, terminate a subprocess that was started when creating the handler instance.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def teardown(self) -> None:
    """Teardown the handler.

    This method should be implemented to, for example, terminate a subprocess
    that was started when creating the handler instance.
    """

update_env

update_env(md: Markdown, config: dict) -> None

Update the Jinja environment.

Parameters:

  • md

    (Markdown) –

    The Markdown instance. Useful to add functions able to convert Markdown into the environment filters.

  • config

    (dict) –

    Configuration options for mkdocs and mkdocstrings, read from mkdocs.yml. See the source code of mkdocstrings.plugin.MkdocstringsPlugin.on_config to see what's in this dictionary.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def update_env(self, md: Markdown, config: dict) -> None:  # noqa: ARG002
    """Update the Jinja environment.

    Arguments:
        md: The Markdown instance. Useful to add functions able to convert Markdown into the environment filters.
        config: Configuration options for `mkdocs` and `mkdocstrings`, read from `mkdocs.yml`. See the source code
            of [mkdocstrings.plugin.MkdocstringsPlugin.on_config][] to see what's in this dictionary.
    """
    self._md = md
    self.env.filters["highlight"] = Highlighter(md).highlight
    self.env.filters["convert_markdown"] = self.do_convert_markdown
    self.env.filters["heading"] = self.do_heading

CollectionError

Bases: Exception

An exception raised when some collection of data failed.

Handlers

Handlers(config: dict)

A collection of handlers.

Do not instantiate this directly. The plugin will keep one instance of this for the purpose of caching. Use mkdocstrings.plugin.MkdocstringsPlugin.get_handler for convenient access.

Parameters:

Methods:

  • get_anchors

    Return the canonical HTML anchor for the identifier, if any of the seen handlers can collect it.

  • get_handler

    Get a handler thanks to its name.

  • get_handler_config

    Return the global configuration of the given handler.

  • get_handler_name

    Return the handler name defined in an "autodoc" instruction YAML configuration, or the global default handler.

  • teardown

    Teardown all cached handlers and clear the cache.

Attributes:

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def __init__(self, config: dict) -> None:
    """Initialize the object.

    Arguments:
        config: Configuration options for `mkdocs` and `mkdocstrings`, read from `mkdocs.yml`. See the source code
            of [mkdocstrings.plugin.MkdocstringsPlugin.on_config][] to see what's in this dictionary.
    """
    self._config = config
    self._handlers: dict[str, BaseHandler] = {}
    self.inventory: Inventory = Inventory(project=self._config["mkdocs"]["site_name"])

inventory instance-attribute

inventory: Inventory = Inventory(project=_config['mkdocs']['site_name'])

seen_handlers property

seen_handlers: Iterable[BaseHandler]

Get the handlers that were encountered so far throughout the build.

Returns:

get_anchors

get_anchors(identifier: str) -> tuple[str, ...]

Return the canonical HTML anchor for the identifier, if any of the seen handlers can collect it.

Parameters:

  • identifier

    (str) –

    The identifier (one that collect can accept).

Returns:

  • tuple[str, ...]

    A tuple of strings - anchors without '#', or an empty tuple if there isn't any identifier familiar with it.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_anchors(self, identifier: str) -> tuple[str, ...]:
    """Return the canonical HTML anchor for the identifier, if any of the seen handlers can collect it.

    Arguments:
        identifier: The identifier (one that [collect][mkdocstrings.handlers.base.BaseHandler.collect] can accept).

    Returns:
        A tuple of strings - anchors without '#', or an empty tuple if there isn't any identifier familiar with it.
    """
    for handler in self._handlers.values():
        fallback_config = getattr(handler, "fallback_config", {})
        try:
            anchors = handler.get_anchors(handler.collect(identifier, fallback_config))
        except CollectionError:
            continue
        if anchors:
            return anchors
    return ()

get_handler

get_handler(name: str, handler_config: dict | None = None) -> BaseHandler

Get a handler thanks to its name.

This function dynamically imports a module named "mkdocstrings.handlers.NAME", calls its get_handler method to get an instance of a handler, and caches it in dictionary. It means that during one run (for each reload when serving, or once when building), a handler is instantiated only once, and reused for each "autodoc" instruction asking for it.

Parameters:

  • name

    (str) –

    The name of the handler. Really, it's the name of the Python module holding it.

  • handler_config

    (dict | None, default: None ) –

    Configuration passed to the handler.

Returns:

  • BaseHandler

    An instance of a subclass of BaseHandler, as instantiated by the get_handler method of the handler's module.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_handler(self, name: str, handler_config: dict | None = None) -> BaseHandler:
    """Get a handler thanks to its name.

    This function dynamically imports a module named "mkdocstrings.handlers.NAME", calls its
    `get_handler` method to get an instance of a handler, and caches it in dictionary.
    It means that during one run (for each reload when serving, or once when building),
    a handler is instantiated only once, and reused for each "autodoc" instruction asking for it.

    Arguments:
        name: The name of the handler. Really, it's the name of the Python module holding it.
        handler_config: Configuration passed to the handler.

    Returns:
        An instance of a subclass of [`BaseHandler`][mkdocstrings.handlers.base.BaseHandler],
            as instantiated by the `get_handler` method of the handler's module.
    """
    if name not in self._handlers:
        if handler_config is None:
            handler_config = self.get_handler_config(name)
        handler_config.update(self._config)
        module = importlib.import_module(f"mkdocstrings_handlers.{name}")
        self._handlers[name] = module.get_handler(
            theme=self._config["theme_name"],
            custom_templates=self._config["mkdocstrings"]["custom_templates"],
            config_file_path=self._config["mkdocs"]["config_file_path"],
            **handler_config,
        )
    return self._handlers[name]

get_handler_config

get_handler_config(name: str) -> dict

Return the global configuration of the given handler.

Parameters:

  • name

    (str) –

    The name of the handler to get the global configuration of.

Returns:

  • dict

    The global configuration of the given handler. It can be an empty dictionary.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_handler_config(self, name: str) -> dict:
    """Return the global configuration of the given handler.

    Arguments:
        name: The name of the handler to get the global configuration of.

    Returns:
        The global configuration of the given handler. It can be an empty dictionary.
    """
    handlers = self._config["mkdocstrings"].get("handlers", {})
    if handlers:
        return handlers.get(name, {})
    return {}

get_handler_name

get_handler_name(config: dict) -> str

Return the handler name defined in an "autodoc" instruction YAML configuration, or the global default handler.

Parameters:

  • config

    (dict) –

    A configuration dictionary, obtained from YAML below the "autodoc" instruction.

Returns:

  • str

    The name of the handler to use.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def get_handler_name(self, config: dict) -> str:
    """Return the handler name defined in an "autodoc" instruction YAML configuration, or the global default handler.

    Arguments:
        config: A configuration dictionary, obtained from YAML below the "autodoc" instruction.

    Returns:
        The name of the handler to use.
    """
    global_config = self._config["mkdocstrings"]
    if "handler" in config:
        return config["handler"]
    return global_config["default_handler"]

teardown

teardown() -> None

Teardown all cached handlers and clear the cache.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def teardown(self) -> None:
    """Teardown all cached handlers and clear the cache."""
    for handler in self.seen_handlers:
        handler.teardown()
    self._handlers.clear()

ThemeNotSupported

Bases: Exception

An exception raised to tell a theme is not supported.

do_any

do_any(seq: Sequence, attribute: str | None = None) -> bool

Check if at least one of the item in the sequence evaluates to true.

The any builtin as a filter for Jinja templates.

Parameters:

  • seq

    (Sequence) –

    An iterable object.

  • attribute

    (str | None, default: None ) –

    The attribute name to use on each object of the iterable.

Returns:

  • bool

    A boolean telling if any object of the iterable evaluated to True.

Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
def do_any(seq: Sequence, attribute: str | None = None) -> bool:
    """Check if at least one of the item in the sequence evaluates to true.

    The `any` builtin as a filter for Jinja templates.

    Arguments:
        seq: An iterable object.
        attribute: The attribute name to use on each object of the iterable.

    Returns:
        A boolean telling if any object of the iterable evaluated to True.
    """
    if attribute is None:
        return any(seq)
    return any(_[attribute] for _ in seq)