在Sphinx生成的文档中对模块属性值进行省略/截断

时间:2014-08-05 18:24:30

标签: python python-sphinx

是否有办法让Sphinx记录的模块属性值被截断:

让我们定义一个模块属性:

import numpy as np

MY_MODULE_ATTRIBUTE = np.linspace(-10, 10, 64)
"""
Defines a very ugly *sphinx* rendered module member.
"""

输出将是这样的(你可以在右边滚动很长时间):

foo module

foo.hello.MY_MODULE_ATTRIBUTE = array([-10. , -9.68253968, -9.36507937, -9.04761905, -8.73015873, -8.41269841, -8.0952381 , -7.77777778, -7.46031746, -7.14285714, -6.82539683, -6.50793651, -6.19047619, -5.87301587, -5.55555556, -5.23809524, -4.92063492, -4.6031746 , -4.28571429, -3.96825397, -3.65079365, -3.33333333, -3.01587302, -2.6984127 , -2.38095238, -2.06349206, -1.74603175, -1.42857143, -1.11111111, -0.79365079, -0.47619048, -0.15873016, 0.15873016, 0.47619048, 0.79365079, 1.11111111, 1.42857143, 1.74603175, 2.06349206, 2.38095238, 2.6984127 , 3.01587302, 3.33333333, 3.65079365, 3.96825397, 4.28571429, 4.6031746 , 4.92063492, 5.23809524, 5.55555556, 5.87301587, 6.19047619, 6.50793651, 6.82539683, 7.14285714, 7.46031746, 7.77777778, 8.0952381 , 8.41269841, 8.73015873, 9.04761905, 9.36507937, 9.68253968, 10. ])
Defines a very ugly sphinx rendered module member.

以非常丑陋的方式包裹或伸展。那种更好的东西会是那种:

foo module

foo.hello.MY_MODULE_ATTRIBUTE = array([-10. , -9.68253968, ..., 9.68253968, 10. ])
Defines a very ugly sphinx rendered module member.

2 个答案:

答案 0 :(得分:2)

属性值由Sphinx的add_directive_header()类的DataDocumenter方法输出。这个猴子补丁可用于截断它:

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

def add_directive_header(self, sig):
    ModuleLevelDocumenter.add_directive_header(self, sig)
    if not self.options.annotation:
        try:
            objrepr = safe_repr(self.object)

            # PATCH: truncate the value if longer than 50 characters
            if len(objrepr) > 50:                  
                objrepr = objrepr[:50] + "..." 

        except ValueError:
            pass
        else:
            self.add_line(u'   :annotation: = ' + objrepr, '<autodoc>')
    elif self.options.annotation is SUPPRESS:
        pass
    else:
        self.add_line(u'   :annotation: %s' % self.options.annotation,
                      '<autodoc>')

DataDocumenter.add_directive_header = add_directive_header

只需将上面的代码添加到conf.py。

答案 1 :(得分:0)

由于我没有指定在哪个上下文/输出中发生截断,我找到了html输出的CSS解决方案:

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

如果可能的话,我宁愿在源头完成,以便修复可用于任何类型的输出。

修改

我遇到了这个:http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-signature 它应该做我需要的,我设法用它替换我的所有签名。当我有一个正确的代码时,我会把它推到这里。