12

I'm currently documenting a whole module with autodoc. However, I define several variables on the module level that contain long lists or dicts. They are included in the documentation together with the values, and the values are unformatted, so it looks like a 10-lines mess. What I want is for the docstring of those variables to be included, but for the values to be omitted or at least nicely formatted.

I've tried to exclude the variable from automodule directive and add it like that:

.. automodule:: foo.bar
   :members:
   :exclude-members: longstuff

   .. py:data:: longstuff

This resulted in that only the variable name was included, whereas both the docstring and the value of longstuff were not present in the documentation.

How can I keep the docstring and get rid of the value (or have it nicely formatted) at the same time?

Lev Levitsky
  • 63,701
  • 20
  • 147
  • 175

1 Answers1

5

There is no simple configuration setting for omitting values of module level variables in the output. But you can do it by modifying the DataDocumenter.add_directive_header() method in autodoc.py. The crucial line in that method is

self.add_line(u'   :annotation: = ' + objrepr, '<autodoc>')

where objrepr is the value.

The following monkey patch added to conf.py works for me:

from sphinx.ext.autodoc import ModuleLevelDocumenter, DataDocumenter

def add_directive_header(self, sig):
    ModuleLevelDocumenter.add_directive_header(self, sig)
    # Rest of original method ignored

DataDocumenter.add_directive_header = add_directive_header
mzjn
  • 48,958
  • 13
  • 128
  • 248
  • On another note, the changes don't happen if I just re-make the pages, but only if I change something in the page source. It happens pretty often and is quite annoying. Is it common? What's the easiest way to ensure the changes will be applied? Looks like it assumes that no changes are needed if the source is intact, which is wrong. – Lev Levitsky Jun 03 '12 at 13:06
  • I'm not sure I understand. I use `make clean html` to ensure that everything is redone from scratch. – mzjn Jun 03 '12 at 13:27
  • I guess that's what I need. Sorry for the dumb question, I just don't happen to use `make` often apart from Sphinx docs :) – Lev Levitsky Jun 03 '12 at 13:29
  • Works for me. Note that if you want this to apply only to specific symbols, you will have to write a fancier function that checks self.name and delegates to the original method if name doesn't match. – Christopher Barber Aug 26 '19 at 16:56