[Python] Why does Sphinx generate indentation errors when attempting to include numpy arrays?

Discussão em 'Python' iniciado por Stack, Abril 5, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to generate documentation using Sphinx based on docstrings. When I attempt to include an array for output (which spans multiple lines, and also has indents on all but the first line) I get an error message : "ERROR: unexpected indentation". As an example:

    """
    >>>SHO.a(3)
    array([[0. +0.j, 1. +0.j, 0. +0.j],
    [0. +0.j, 0. +0.j, 1.41421356+0.j],
    [0. +0.j, 0. +0.j, 0. +0.j]])

    """


    would produce SHO.py:docstring of SHO:4: ERROR: Unexpected indentation. However, the format of the above code looks similar to what is found in scipy docs, such as the examples of the fft function; the corresponding source code with docstring can be found here

    The full document which generates the errors is shown below:

    """This SHO.py module generates the matrix form for several common operators in the energy eigenbasis of the harmonic oscillator.

    Functions within can generate :math:`\\hat{x}, \\hat{p}, \\hat{a}^+, \\hat{a}, \\hat{H}`, and second moments of `\\hat{x}` and `\\hat{p}`

    Example
    -------
    >>>import SHO
    >>>SHO.a(3)
    array([[0. +0.j, 1. +0.j, 0. +0.j],
    [0. +0.j, 0. +0.j, 1.41421356+0.j],
    [0. +0.j, 0. +0.j, 0. +0.j]])
    >>>SHO.a_dagger(3)
    array([[0. +0.j, 0. +0.j, 0. +0.j],
    [1. +0.j, 0. +0.j, 0. +0.j],
    [0. +0.j, 1.41421356+0.j, 0. +0.j]])

    The matrices above are used to calculate the energy using the relation :math:`H = a^+a + 1/2`

    >>>import numpy as np
    >>>SHO.a_dagger(3)@SHO.a(3) + 0.5 * np.eye(3)
    array([[0.5+0.j, 0. +0.j, 0. +0.j],
    [0. +0.j, 1.5+0.j, 0. +0.j],
    [0. +0.j, 0. +0.j, 2.5+0.j]])

    """


    which generates the same error on lines 10,14, and 22.

    Continue reading...

Compartilhe esta Página