You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Sphinx包含numpy数组时为何产生缩进错误?

Sphinx生成文档时numpy数组多行缩进报错的解决方法

当用Sphinx基于文档字符串生成技术文档时,若文档中包含跨多行且首行外有额外缩进的numpy数组输出,会触发ERROR: unexpected indentation错误,比如你提供的文档中第10、14、22行均出现该问题。

解决方法

方法1:调整数组缩进以匹配doctest规则

Sphinx处理doctest风格的示例时,要求输出块的所有行保持一致的缩进级别。只需将numpy数组的后续行缩进调整为与array(...)所在行的起始位置对齐即可:

修改前(错误示例):

>>>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(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]])

这种方法保留了doctest的自动测试功能,同时避免缩进错误。

方法2:用代码块包裹示例(放弃doctest测试)

如果希望保留数组的缩进格式,可将整个示例用.. code-block:: python标记包裹,Sphinx会将其视为纯代码块渲染,不再检查doctest缩进规则:

修改后的完整文档字符串:

"""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
-------
.. code-block:: python

    >>>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`

.. code-block:: python

    >>>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]])
        
"""

原因说明

Sphinx的doctest解析器会将>>>开头的行识别为输入命令,后续无>>>的行视为输出结果,输出块内的所有行必须保持相同缩进级别。你参考的scipy文档示例中,数组后续行均与array起始位置对齐,无额外缩进,因此不会触发错误。

内容的提问来源于stack exchange,提问作者Idieh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 13:40:54