From ccf7c19019fbfffaaab85797dcf8d14f7c43c7f7 Mon Sep 17 00:00:00 2001 From: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> Date: Wed, 12 Jun 2024 10:49:19 +0200 Subject: [PATCH] DOC: Add autodoc section "Ensuring the code can be imported" This explains the requirements for importablilty (can be found and dependencies can be resolved). It also explains two common approaches how this can be achieved. --- doc/usage/extensions/autodoc.rst | 39 ++++++++++++++++++++++++++------ 1 file changed, 32 insertions(+), 7 deletions(-) diff --git a/doc/usage/extensions/autodoc.rst b/doc/usage/extensions/autodoc.rst index c920de84303..b094d50f7cb 100644 --- a/doc/usage/extensions/autodoc.rst +++ b/doc/usage/extensions/autodoc.rst @@ -12,13 +12,6 @@ This extension can import the modules you are documenting, and pull in documentation from docstrings in a semi-automatic way. -.. note:: - - For Sphinx (actually, the Python interpreter that executes Sphinx) to find - your module, it must be importable. That means that the module or the - package must be in one of the directories on :data:`sys.path` -- adapt your - :data:`sys.path` in the configuration file accordingly. - .. warning:: :mod:`~sphinx.ext.autodoc` **imports** the modules to be documented. If any @@ -44,6 +37,38 @@ docstrings to correct reStructuredText before :mod:`autodoc` processes them. .. _NumPy: https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard +Ensuring the code can be imported +--------------------------------- + +:mod:`~sphinx.ext.autodoc` analyses the code and docstrings by introspection after +importing the modules. For importing to work. you have to make sure that your modules +can be found by sphinx and that dependencies can be resolved (if your module does +``import foo``, but ``foo`` is not available in the python environment that Sphinx +runs in, your module import will fail). + +There are two ways to ensure this: + +1. Use an environment that contains your package and Sphinx. This can e.g. be your + local dev environment (with an editable install), or an environment in CI in which + you install Sphinx and your package. The regular installation process ensures that + your package can be found by sphinx and that all dependencies are available. + +2. It is alternatively possible to patch the Sphinx run so that it can operate directly + on the sources; e.g. if you want to be able to do a sphinx build from a source + checkout. + + - Patch ``sys.path`` in your Sphinx :file:`conf.py` to include the folder of your + sources. E.g. if you have a repository structure with :file:`doc/conf.py` and + your package is at :file:`src/mypackage`, then you sould add:: + + sys.path.insert(0, os.path.abspath('../src')) + + to your :file:`conf.py`. + + - To cope with missing dependencies, specify the missing modules in + :confval:`autodoc_mock_imports`. + + Directives ----------