使用Python Sphinx引用长名称
我正在为我的Python模块编写文档(使用Sphinx和reST),并且发现当交叉引用其他Python对象(模块,类,函数等)时,完整的对象名最终变得非常长。通常它的长度超过80个字符,我不惜一切代价避免。
这是一个例子:
def exampleFunction():
'''Here is an example docstring referencing another
:class:`module1.module2.module3.module4.module5.ReallyLongExampleClassName`
'''
问题是,在为 ReallyLongExampleClassName
类创建文档时,我为完整路径名生成了它module1.module2.module3.module4.module5.ReallyLongExampleClassaName
。
我想知道是否有办法解决这个问题?我尝试了以下方法,但没有成功:
1)在模块名称的中间添加换行符。例:
:class:`module1.module2.module3.module4.
module5.ReallyLongExampleClassName`
2)以其他方式(但仍可导入Python)引用类名。例:
:class:`module1.module2.ReallyLongClassName`
我认为,由于的文档ReallyLongClassName
与完整路径名绑定,因此Sphinx无法将缩短的版本与全名版本相关联。
编辑04/05/2012 :
根据j13r的答案/建议(请参见下文),我尝试了以下操作:
:class:`module1.module2.module3.module4.module5\
ReallyLongExampleClassName`
这成功地工作了。使此功能生效的唯一警告是,第二行之前不能有空格(在文档字符串中使用此字符串时,这非常令人沮丧)。因此,使我的原始示例生效,它看起来像:
def exampleFunction():
'''Here is an example docstring referencing another
:class:`module1.module2.module3.module4.module5.\
ReallyLongExampleClassName`
'''
很好,很丑。如果您要在空格之前ReallyLongExampleClassName
将其缩进到与其上方的行相同的高度,则输出将包括空格,因此Sphinx会尝试引用module1.module2.module3.module4.module5.ReallyLongExampleClassName
。
我还应该注意,我尝试了其他两种变体,但没有用:
# Note: Trying to put a space before the '\'
:class:`module1.module2.module3.module4.module5. \
ReallyLongExampleClassName`
# Note: Trying to leave out the '\'
:class:`module1.module2.module3.module4.module5.
ReallyLongExampleClassName`
我一直在寻找一种不涉及破坏docstring格式的解决方案,但是我想它可以做到……我想我实际上更喜欢一行超过80个字符的行。
感谢j13r的回答!
-
根据sphinx文档(https://www.sphinx-
doc.org/en/master/usage/restructuredtext/domains.html#cross-referencing-
python-objects),可以在目标类之前使用点::class:`.ReallyLongExampleClassName`
要么
:class:`.module5.ReallyLongExampleClassName`
让狮身人面像搜索该类:
…如果名称前加点号,但未找到完全匹配的内容,则将目标作为后缀,并搜索带有该后缀的所有对象名称。例如,:py:meth:
.TarFile.close
引用tarfile.TarFile.close()函数,即使当前模块不是tarfile。由于这可能会变得模棱两可,因此,如果可能存在多个匹配项,您将收到Sphinx的警告。