Get “flat” member output for sphinx automodule

2020-06-08 14:16发布

问题:

I'm using the Sphinx autodoc extension to document a module, and I'd like to get a flat list of the module's members in the documentation output.

I tried using the following:

.. automodule:: modname
   :members:

However, there are two problems with this:

  1. It includes the module's docstring, which I don't want here.

  2. The name of each entry is prefixed with "modname.", which is completely redundant (since this page is specifically for documenting this module)

However, I haven't been able to find any config options that would let me selectively disable these two aspects while still getting the automatic listing of all of the module members.

My current plan is to just use autofunction (etc) and explicitly enumerate the members to be documented, but I'd still like to know if I missed an easy way to achieve what I originally wanted.

Update: I at least found a workaround for the second part: set add_module_names=False in conf.py. That's a global setting though, so it doesn't really answer my original question.

回答1:

Looking at this answer to a similar question, I've found that you can use the autodoc-process-docstring event to remove the docstrings from modules appending the following code to your conf.py:

def skip_modules_docstring(app, what, name, obj, options, lines):
    if what == 'module':
        del lines[:]

def setup(app):
    app.connect('autodoc-process-docstring', skip_modules_docstring)

Note that the del statement is needed because, according to the documentation, the modification to lines must happend in place (it you create a new object, it doesn't work).

Finally, you can also use name to filter the docstrings of just a few modules while keeping the ones from others.