mkdocs and Python Libraries

Documentation for libraries is handy. Automatically generating most of it from source code is even more handy.

Here’s a quick how-to on setting up mkdocs with the mkdocstrings plugin to automagically build docs for your project.

mkdocs.yml

This goes in the root directory of your project.

It sets various things like the Name of the site, theme etc.

site_name: aussiebb
theme:
  name: "material"

plugins:
  - search:
  - mkdocstrings:
      default_handler: python
      handlers:
        python:
          rendering:
            show_source: true
      watch:
        - "aussiebb/"

nav:
  - "Home": README.md
  - "aussiebb": aussiebb.md

Relevant documentation:

docs/aussiebb.md

This template tells mkdocstrings to document the aussiebb module. If you were documenting the cheese module you’d put that there. You can list any accessible module.


::: aussiebb

.github/workflows/docs.yml

This is a github workflow to automatically deploy the docs when you push to the master branch.

name: Build and deploy mkdocs to github pages
on:
  push:
    branches:
      - master
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/[email protected]
        with:
          fetch-depth: 0
      - name: Setup Python
        uses: actions/[email protected]
        with:
          python-version: '3.9'
      - name: Install dependencies
        run: |
          python3 setup.py install
          python3 -m pip install --upgrade pip
          python3 -m pip install mkdocs mkdocstrings mkdocs-material          
      - name: Build site
        run: mkdocs build
      - name: Deploy
        uses: peaceiris/[email protected]
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./site

On https://github.com/<username>/<repo>/settings/pages you configure the github pages integration as follows:

github pages configuration

One last thing..

To make the README file automagically become the home page you have to make a link to it on the filesystem in the docs/ directory:

$ ln -s ../README.md ./docs/

Example source code

I’ve spun up a quick example set of files here: https://github.com/yaleman/py-auto-docs/

Which generated the following site: https://yaleman.github.io/py-auto-docs/

Extra notes



#mkdocs #python #documentation #mkdocstrings #howto