gpt4 book ai didi

python - Sphinx 生成的文档中模块属性值的省略/截断

转载 作者:行者123 更新时间:2023-11-30 23:20:59 25 4
gpt4 key购买 nike

有没有办法让 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.

这会以一种非常丑陋的方式包裹或拉伸(stretch)。更好的东西会是这样的:

foo module

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

最佳答案

属性值由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即可。

关于python - Sphinx 生成的文档中模块属性值的省略/截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25145817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com