首页 > 解决方案 > 如何使用 Sphinx 在 Python 文档字符串中指示有效范围?

问题描述

有没有办法使用 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 文档字符串中记录这一点?

标签: pythonpython-sphinxdocstring

解决方案


默认情况下,Python 模块是 UTF-8编码的,因此字符将正常呈现。可以使用 Unicode 字符或使用文档字符串中的前缀的相应十六进制代码来编写字符串文字。u这使得数学的 Unicode 范围可以写在文档字符串中。

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

u使用 Google 样式的文档字符串,使用显式和前缀编写的具有 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 有几个扩展允许将它们输出为 HTML


推荐阅读