【问题标题】:How to indicate a valid range in a Python docstring using Sphinx?如何使用 Sphinx 在 Python 文档字符串中指示有效范围?
【发布时间】:2020-09-26 23:10:05
【问题描述】:

有没有办法使用 Sphinx 在 Python 文档字符串中指示“有效范围”?例如,考虑以下线性函数。

def f(m, x, b):
    """
    Returns the `y` value of a linear function using slope-intercept form.
    
    :param x: The x-axis value.
    :type x: float
    :param m: The slope of the linear function.
    :type m: float
    :param b: The y-intercept.
    :type b: float
    """
    if x < 0:
        raise ValueError('The min "x" value of this function is 0')
    return m * x + b

有没有办法将x 的域表示为“x 必须大于零”?或者用区间表示法,[0, infinity]

具体来说,有没有办法使用 Sphinx 在 Python 文档字符串中记录这一点?

【问题讨论】:

  • 为什么不把它附加到定义中呢? :param x: The x-axis value. The min "x" value of this function is 0.
  • @StevePiercy 我可以这样做,但我希望 Sphinx 中可能有一个选项(或其他东西)可以为函数的 domain 添加一些特殊格式,所以当呈现后查看文档。
  • 没有这个功能。 Autodoc 只解析 Python 域中的方法签名和文档字符串,而不是任意代码。
  • 以一种惯用的 Pythonic 方式定义 domain 将是在 Sphinx 将呈现的文档字符串中定义一个 doctest(取决于 sphix 主题)作为警告。注意,doctest 是一个简单的 Python 结构,主要用于表达简单的案例。对于更详细的用例,您将实现一个domain 类,记录它并交叉引用它。文档的关键是一致性,您可以口头说明该域正在使用某种形式的反引号或粗体突出显示。
  • 您可能还想考虑switch from basic ReST syntax 的优势。

标签: python python-sphinx docstring


【解决方案1】:

默认Python modules are UTF-8 编码,因此字符将正常呈现。可以使用 Unicode 字符或文档字符串中相应的 hexadecimal code using the u 前缀来编写字符串文字。这使得Unicode range for math 可以写入文档字符串。

Python 将程序文本读取为 Unicode 代码点;源文件的编码可以通过编码声明给出,默认为 UTF-8,详见 PEP 3120。

使用 Google 样式的文档字符串,显式编写并带有 u 前缀的 Unicode 字符示例字符串:

def f(m, x, b) -> float:
    """
    Returns the `y` value of a linear function using slope-intercept form.

    Args:
        x (float): The x-axis value.
        m (float): The slope of the linear function.
        b (float): The y-intercept.
    Returns:
        float: The y-axis value.
    Raises:
        ValueError: Value of `x` ∈ [0, ∞], or `x` \u2208\u005B 0, \u221E\u005D.

    """
    if x < 0:
        raise ValueError('The min "x" value of this function is 0')
    return m * x + b

结果:

如果您想编写更复杂的数学表达式Sphinx has several extensions that allow to output them as HTML,这适用于简单的方程式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多