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:
-
MkdocstringsPlugin
–An
mkdocs
plugin. -
PluginConfig
–The configuration options of
mkdocstrings
, written inmkdocs.yml
.
Functions:
-
list_to_tuple
–Decorater to convert lists to tuples in the arguments.
Attributes:
-
InventoryImportType
– -
InventoryLoaderType
– -
P
– -
R
– -
log
–
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:
-
get_handler
–Get a handler by its name. See mkdocstrings.handlers.base.Handlers.get_handler.
-
on_config
–Instantiate our Markdown extension.
-
on_env
–Extra actions that need to happen after all Markdown rendering and before HTML rendering.
-
on_post_build
–Teardown the handlers.
Attributes:
-
css_filename
– -
handlers
(Handlers
) –Get the instance of mkdocstrings.handlers.base.Handlers for this plugin/build.
-
inventory_enabled
(bool
) –Tell if the inventory is enabled or not.
-
plugin_enabled
(bool
) –Tell if the plugin is enabled or not.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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:
-
Handlers
–An instance of mkdocstrings.handlers.base.Handlers (the same throughout the build).
inventory_enabled
property
inventory_enabled: bool
plugin_enabled
property
plugin_enabled: bool
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:
-
BaseHandler
–An instance of a subclass of
BaseHandler
.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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
on_env
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
on_post_build
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
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
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={})
list_to_tuple
Decorater to convert lists to tuples in the arguments.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/plugin.py
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:
-
AutoDocProcessor
–Our "autodoc" Markdown block processor.
-
MkdocstringsExtension
–Our Markdown extension.
Attributes:
-
log
–
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:
Attributes:
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
regex
class-attribute
instance-attribute
run
run(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.
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
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 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 |
|
test
Match our autodoc instructions.
Parameters:
Returns:
-
bool
–Whether this block should be processed or not.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
MkdocstringsExtension
Bases: Extension
Our Markdown extension.
It cannot work outside of mkdocstrings
.
Parameters:
-
config
dict
) –The configuration items from
mkdocs
andmkdocstrings
that must be passed to the block processor when instantiated inextendMarkdown
. -
handlers
Handlers
) –The handlers container.
-
autorefs
AutorefsPlugin
) –The autorefs plugin instance.
-
**kwargs
Any
, default:{}
) –Keyword arguments used by
markdown.extensions.Extension
.
Methods:
-
extendMarkdown
–Register the extension.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/extension.py
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
mkdocstrings.handlers.base
Base module for handlers.
This module contains the base classes for implementing handlers.
Classes:
-
BaseHandler
–The base handler class.
-
CollectionError
–An exception raised when some collection of data failed.
-
Handlers
–A collection of handlers.
-
ThemeNotSupported
–An exception raised to tell a theme is not supported.
Functions:
-
do_any
–Check if at least one of the item in the sequence evaluates to true.
Attributes:
BaseHandler
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
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
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.
collect
collect(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.
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
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
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
get_anchors
get_anchors(data: CollectorItem) -> tuple[str, ...]
Return the possible identifiers (HTML anchors) for a collected item.
Parameters:
-
data
CollectorItem
) –The collected data.
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
get_extended_templates_dirs
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:
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
get_headings
Return and clear the headings gathered so far.
Returns:
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
get_templates_dir
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:
-
ModuleNotFoundError
–When no such handler is installed.
-
FileNotFoundError
–When the templates directory cannot be found.
Returns:
-
Path
–The templates directory path.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
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:
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
render
Render a template using provided data and configuration options.
Parameters:
-
data
CollectorItem
) –The collected data to render.
-
config
Mapping[str, Any]
) –The handler's configuration options.
Returns:
-
str
–The rendered template as HTML.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
teardown
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 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
andmkdocstrings
, read frommkdocs.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
CollectionError
Bases: Exception
An exception raised when some collection of data failed.
Handlers
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:
-
config
dict
) –Configuration options for
mkdocs
andmkdocstrings
, read frommkdocs.yml
. See the source code of mkdocstrings.plugin.MkdocstringsPlugin.on_config to see what's in this dictionary.
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:
-
inventory
(Inventory
) – -
seen_handlers
(Iterable[BaseHandler]
) –Get the handlers that were encountered so far throughout the build.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
inventory
instance-attribute
seen_handlers
property
seen_handlers: Iterable[BaseHandler]
Get the handlers that were encountered so far throughout the build.
Returns:
-
Iterable[BaseHandler]
–An iterable of instances of
BaseHandler
-
Iterable[BaseHandler]
–(usable only to loop through it).
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:
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
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 theget_handler
method of the handler's module.
Source code in .venv/lib/python3.11/site-packages/mkdocstrings/handlers/base.py
get_handler_config
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
get_handler_name
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
teardown
Teardown all cached handlers and clear the cache.
ThemeNotSupported
Bases: Exception
An exception raised to tell a theme is not supported.
do_any
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.