Running Sphinx on a single Python file

31 Aug '19

Python’s default and awesome documentation generator is Sphinx. And while it makes sense that Markdown is too limited for great documentation, I find reStructuredText to be tricky at times, since I don’t use it that regularly.

For standalone documents, Docutils works great, and some Python IDEs have reStructuredText support. Of course, for small projects, a README is probably enough. But it’s undeniable Sphinx’ documentation is beautiful, and having features like autodoc or intersphinx is convenient. Luckily, it’s easy to run Sphinx and autodoc on a single file module. Bit of a niche use-case, I know. Why should small projects not have great documentation?

As per usually, you start with sphinx-quickstart. To save time, here’s my final conf.py file:

import os
import sys

# enable autodoc to load local modules
sys.path.insert(0, os.path.abspath("."))

project = "<project>"
copyright = "2019, Toby Fleming"
author = "Toby Fleming"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.intersphinx"]
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
templates_path = ["_templates"]
html_theme = "alabaster"
html_static_path = ["_static"]
intersphinx_mapping = {
    "python": ("https://docs.python.org/3", None)
}
html_theme_options = {"nosidebar": True}

index.rst can also be stripped down completely (it’s the only file you need with autodoc). Assuming the Python file is <project>.py, this works:

<project>
=========

.. automodule:: <project>
   :members:

Building the documentation works and outputs documentation for a single file:

$ sphinx-build -b html . _build
$ open _build/index.html

By the way, instead of using (the de facto default) html output, singlehtml works great in this case. An example of this is in my repo uuid_conv.

Python

Newer Older