我正在为我的 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`
我一直在寻找一种不涉及破坏文档字符串格式的解决方案,但我想它会做...我想我实际上更喜欢超过 80 个字符的行。
感谢 j13r 的回答!
最佳答案
根据 sphinx 文档 (https://www.sphinx-doc.org/en/master/usage/restructuredtext/domains.html#cross-referencing-python-objects),您可以在目标类之前使用一个点:
:class:`.ReallyLongExampleClassName`
或
:class:`.module5.ReallyLongExampleClassName`
然后让 sphinx 搜索类:
... if the name is prefixed with a dot, and no exact match is found, the target is taken as a suffix and all object names with that suffix are searched. For example, :py:meth:
.TarFile.close
references the tarfile.TarFile.close() function, even if the current module is not tarfile. Since this can get ambiguous, if there is more than one possible match, you will get a warning from Sphinx.
关于python - 使用 Python Sphinx 引用长名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10034303/