Search code examples
pythonpython-sphinxdocstring

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? 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"? Or in interval notation, [0, infinity].

Specifically, is there a way to document this in a Python docstring using Sphinx?


Solution

  • By default 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 available to be written in the docstring.

    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.

    Example string literals with Unicode characters written both explicitly and with u prefix, using a Google style docstring:

    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:

    enter image description here

    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.