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
因为我没有说明我想在哪种情况下或输出中进行截断,所以我找到了一个适用于HTML输出的CSS解决方案:
.ellipsis {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
如果可以的话,我更希望在源头就解决这个问题,这样修复就可以适用于任何类型的输出。
编辑:
我发现了这个链接:http://sphinx-doc.org/ext/autodoc.html#event-autodoc-process-signature。它应该能满足我的需求,我已经用它替换了我所有的签名。当我有了合适的代码时,我会把它放在这里。
3
这个属性值是通过Sphinx的 DataDocumenter
类里的 add_directive_header()
方法输出的。你可以用这个小技巧来缩短它:
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 文件中就可以了。