0

I'm trying to make documentation using Sphinx for a module which I've recently started creating. How do I organise my code so that both autodoc and python can read it properly?

I have the following file structure in which inference.py imports a Class from create_data.py:

[meg_analysis]
  |
  |-[docs]
  |    |
  |    |-{files created by apidoc}
  |
  |-create_data.py
  |-inference.py

sphinx-apidoc creates a file called meg_analysis.rst which contains ReST directives including:

.. automodule:: meg_analysis.inference
   :members:
   :undoc-members:
   :show-inheritance:

When I run make html, I get this message:

WARNING: autodoc: failed to import module 'inference' from module 'meg_analysis'; the following exception was raised:
No module named 'create_data'

I can fix this error by changing the import statement from from create_data import SimulatedData to from meg_analysis.create_data import SimulatedData.

The issue is then that now when I run python inference.py I get ModuleNotFoundError: No module named 'meg_analysis' and PyCharm starts underlining all of its uses in red.

Is there a way that I can get autodoc to successfully document all of my files without having to include a module-level import every time I want to use something from another part of the module? Am I structuring my code wrongly in some fundamental way?

evanr70
  • 139
  • 10
  • Is `meg_analysis` supposed to be a package and `inference` a submodule of that package? Then there should be a `__init__.py` file in the `meg_analysis` directory. `automodule:: meg_analysis.inference` means "document the inference module in the meg_analysis package". – mzjn Aug 27 '19 at 17:47
  • Yes, that's correct. I do actually have a `__init__.py` in `meg_analysis` but it's empty. Should I have populated it with something? – evanr70 Aug 27 '19 at 17:50
  • You don't have to populate `__init__.py`. It can be empty. – mzjn Aug 27 '19 at 18:10
  • These kinds of issues can be a bit difficult to diagnose without a [mcve]. Does `sys.path` (set via PYTHONPATH in PyCharm?) contain an entry that points to the directory above `meg_analysis`? If not, the "No module named 'meg_analysis'" error is expected. – mzjn Aug 27 '19 at 18:11

1 Answers1

0

Adding both the project directory and the directory above fixed the issue.

In the conf.py file created by sphinx-quickstart, add the lines

import sys
sys.path.insert(0, '/Users/{USER_NAME}/PycharmProjects/')
sys.path.insert(0, '/Users/{USER_NAME}/PycharmProjects/meg_analysis/')

Not sure if this is the best solution, but it seems to work.

evanr70
  • 139
  • 10