Sphinx: how to exclude imports in automodule?

There is a solution with mocking:

http://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#confval-autodoc_mock_imports

Just add the following line to conf.py (RPi and serial are examples):

autodoc_mock_imports = ["RPi", 'serial']

There is no way to tell Sphinx to exclude some imports. When using autodoc, all documented modules must be cleanly importable.

You might be able to work around the problem by doing some mocking. Here is an article describing the solution to a problem that seems quite similar to yours: http://blog.rtwilson.com/how-to-make-your-sphinx-documentation-compile-with-readthedocs-when-youre-using-numpy-and-scipy/. Here is a small code sample (intended to be added to conf.py):

import mock

MOCK_MODULES = ['numpy', 'matplotlib', 'matplotlib.pyplot']
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock()

You might might need to install python-mock for the above to work: sudo apt-get install python-mock

Update

Since Sphinx 1.3, it is easier to set up the mocking. Just add the modules to be mocked to the autodoc_mock_imports configuration value.


Besides mocking modules, I also had to mock calls that only made sense in my embedded system (for example mocking a call to a function read_reg() from the module examplemod that reads a register from an FPGA via SPI).

import mox as mox 
import examplemod
m = mox.Mox()
m.StubOutWithMock(examplemod, 'read_reg')

Note that you need python-mox: sudo apt-get install python-mox

Reference: How to generate sphinx documentation for python code running in an embedded system