python-sphinx - Python 代码中注释和文档字符串的基本语法

标签 python-sphinx docstring sphinx-napoleon

我正在学习如何使用 Sphinx 为我的代码创建文档。在我看到一些这样的例子之后:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
    if imag == 0.0 and real == 0.0: return complex_zero
    ...
评论中使用什么语言让 Sphinx 理解并捕获它们?
如果没有这种语法和逻辑,Sphinx 在我的代码中看不到注释,并且当我生成 HTML 时,模块是空的。
这里有一个例子:
enter image description here

最佳答案

您必须将注释与文档字符串(全称为“文档字符串”)区分开来。
PEP8 and notice docstrings apply only to模块、函数、类和方法。对于提到的对象,您可以申请 your_object.__doc__以编程方式检索文档字符串;变量没有文档字符串。
关于你的例子:

def complex(real=0.0, imag=0.0):
    """Form a complex number.

    Keyword arguments:
    real -- the real part (default 0.0)
    imag -- the imaginary part (default 0.0)

    """
Sphinx 将检索的文档字符串中可以使用 3 种流行的语法:
  • reST 是基本语法。
  • Numpy 样式的文档字符串。
  • 谷歌风格的文档字符串。

  • 规范是在 Numpy 或 Google 风格之间进行选择(目前它们提供更好的可读性和功能,以及风格指南)。要使这些工作,您需要使用 Sphinx-Napoleon extension ,看看官方文档中的概述。

    关于python-sphinx - Python 代码中注释和文档字符串的基本语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62545038/

    相关文章:

    python - 从 Sphinx 文档中删除单词 "module"

    python - Sphinx graphviz继承图增加节点大小

    pycharm - 自动重新格式化文档字符串以尊重右边距

    python - 记录同一函数的不同参数可能性

    python-sphinx - 你是否应该始终记录函数,即使是多余的(特别是 python)?

    python - 构建sphinx文档时导入模块失败

    python - python的sphinx中var、cvar、ivar有什么区别?

    python - 包括在文档字符串中记录吗?

    Python:未更新文档字符串

    python - 如何在 Sphinx 处理的文档字符串中表示单个参数或返回值的多种类型?