Skip to content Skip to sidebar Skip to footer

Ellipsis / Truncation On Module Attribute Value In Sphinx Generated Documentation

Is there a way to have a module attribute value documented by Sphinx to be truncated: Let's define a module attribute: import numpy as np MY_MODULE_ATTRIBUTE = np.linspace(-10, 10

Solution 1:

The attribute value is output by the add_directive_header() method of Sphinx's DataDocumenter class. This monkey patch can be used to truncate it:

from sphinx.ext.autodoc import DataDocumenter, ModuleLevelDocumenter, SUPPRESS
from sphinx.util.inspect import safe_repr

defadd_directive_header(self, sig):
    ModuleLevelDocumenter.add_directive_header(self, sig)
    ifnot self.options.annotation:
        try:
            objrepr = safe_repr(self.object)

            # PATCH: truncate the value if longer than 50 charactersiflen(objrepr) > 50:                  
                objrepr = objrepr[:50] + "..."except ValueError:
            passelse:
            self.add_line(u'   :annotation: = ' + objrepr, '<autodoc>')
    elif self.options.annotation is SUPPRESS:
        passelse:
        self.add_line(u'   :annotation: %s' % self.options.annotation,
                      '<autodoc>')

DataDocumenter.add_directive_header = add_directive_header

Just add the code above to conf.py.

Solution 2:

Since I didn't specified in which context / output I wanted that truncation to happen, I found a CSS solution for the html output:

.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

I would rather prefer that to be done at the source if possible, so that the fix is available for any kind of output.

Edit:

I came across this: http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-signature It should do what I need, I managed to replace all my signatures with it. When I have a proper code I will push it here.

Post a Comment for "Ellipsis / Truncation On Module Attribute Value In Sphinx Generated Documentation"