How to publish code docstrings in mkdocs and mkdocs-material


If you use mkdocs and you want to publish your code docstrings as documentation, mkdocstrings1 is the way to go.

Here’s how I use it.

First you need to install it, for which you need mkdocstrings as well as the language handlers. For Python:

$ uv add 'mkdocstrings[python]'  # or pip install 'mkdocstrings[python]'

Then, add it to your config file:

mkdocs.yml
 ...
 plugins:
+  - mkdocstrings
 ...

Finally, you can reference your code within your documentation. Here’s a class that contains some well documented error states, that fit nicely within a page of our documentation:

recipients.md
::: app.core.models.campaign_recipients.ErrorMessages
    options:
        show_source: false
        show_root_heading: true
        heading_level: 2

Something that can catch you out is the directory structure. Usually I set up app and docs top-level folders, but run my commands from the folder that contains them both:

project_folder
  | - app/
  | - docs/

To serve the documentation:

$ uv run mkdocs serve -a 127.0.0.1:8123
-> Serving on http://127.0.0.1:8123/

Footnotes

  1. mkdocstrings usage (official documentation)