如何使用 Sphinx 在 Python 文档字符串中指示有效范围?

How to indicate a valid range in a Python docstring using Sphinx?

有没有办法使用 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 文档字符串中对此进行记录?

默认Python modules are UTF-8 encoded so the characters are going to render normally. The string literals can be written using the Unicode character or corresponding hexadecimal code using the u prefix in the docstring. This makes the Unicode range for math 可写入文档字符串。

Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details.

使用 Google 风格的文档字符串,使用 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