[英]How to indicate a valid range in a Python docstring using Sphinx?
Is there a way to indicate a "valid range" in a Python docstring using Sphinx?有没有办法使用 Sphinx 在 Python 文档字符串中指示“有效范围”? For example, consider the following linear function.例如,考虑以下线性函数。
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
Is there a way to indicate the domain of x
to be something like "x must be greater than zero"?有没有办法将x
的域表示为“x 必须大于零”之类的东西? Or in interval notation, [0, infinity]
.或者在区间符号中, [0, infinity]
。
Specifically, is there a way to document this in a Python docstring using Sphinx?具体来说,有没有办法使用 Sphinx 在 Python 文档字符串中记录这一点?
By default Python modules are UTF-8 encoded so the characters are going to render normally.默认情况下, Python 模块采用 UTF-8编码,因此字符将正常呈现。 The string literals can be written using the Unicode character or corresponding hexadecimal code using the u
prefix in the docstring.字符串文字可以使用 Unicode 字符或使用文档字符串中的u
前缀的相应十六进制代码编写。 This makes the Unicode range for math available to be written in the docstring.这使得数学的Unicode 范围可以写入文档字符串。
Python reads program text as Unicode code points; Python 将程序文本读取为 Unicode 代码点; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details.源文件的编码可以由编码声明给出,默认为 UTF-8,详情请参阅 PEP 3120。
Example string literals with Unicode characters written both explicitly and with u
prefix, using a Google style docstring:使用 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
The result:结果:
This works fine for simple equations, if you want to write more sophisticated mathematical expressions Sphinx has several extensions that allow to output them as HTML .这适用于简单的方程,如果你想编写更复杂的数学表达式, Sphinx 有几个扩展,允许将它们输出为 HTML 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.