pythonflaskpython-sphinxpython-venvautodoc

sphinx.ext.autodoc: ModuleNotFoundError for external packages


I want to start documenting my flask-based application with Sphinx. Currently, I am trying to figure how to use the autodoc extension. My local modules are all found, but the imports of external libraries does not work in sphinx.

I have all my requirements in a requirements.txt file, so I hope that sphinx could extract the packages/modules form there. I am testing the sphinx on my local machine in an env. Therefore I already added:

import os
import sys
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('~/envs'))

to myproject/docs/source/config.py. Which worked for my project-internal modules but not further.

So, running sphinx-build -M html docs/source/ docs/build/ causes this error:

WARNING: Failed to import myproject.errors.
Possible hints:
* ModuleNotFoundError: No module named 'flask'
* KeyError: 'myproject'
building [mo]: targets for 0 po files that are out of date
writing output... 
building [html]: targets for 0 source files that are out of date
updating environment: 0 added, 1 changed, 0 removed
reading sources... [100%] api
WARNING: autodoc: failed to import module 'errors' from module 'myproject'; the following exception was raised:
No module named 'flask' [autodoc.import_object]

As an mwe I created myproject/docs/source/api.rst:

API
===

.. autosummary::
   :toctree: generated

.. automodule:: myproject.errors
    :members:
    :imported-members:

To double-check, whether all of the dependencies are installed, I ran `

(envs) user@machine:~/git/myproject$ pip freeze | grep -F "Flask"
Flask==2.3.3

To exclude any problems, that could be flask-specific, I tried to mock it via autodoc_mock_imports=['flask'] but this shifts the problem to all other external modules one by one.


Solution

  • Thank you very much, mzjn! Your hints were correct. I was curiously running all python commands in the venv but the sphinx-build. I proofed this assumptions by adding

    sys.path.append(os.path.abspath('../../'))
    print('Sphinx runs with the following prefix:'+sys.prefix)
    

    to my conf.py, which I got from wpercy and I will leave these lines there, for later debugging. After knowing this I tried to do it as migonzalvar describes it:

    With the environment activated:

    $ source /home/migonzalvar/envs/myenvironment/bin/activate
    $ pip install sphinx
    $ which sphinx-build
    /home/migonzalvar/envs/myenvironment/bin/sphinx-build
    

    Which still did not work. Only after I deactivated the venv and uninstalled sphinx globally via pip uninstall sphinx, sphinx-build started to use the venv (as I intended).