在 docstring 中添加 doctest?

解读

国内大型互联网公司与科研院所对 Matplotlib 的二次开发岗位,普遍把“可执行文档”视为代码质量门禁。面试官抛出“给 docstring 补 doctest”,并不是让你写几行 >>> 就过关,而是考察三件事:

  1. 是否理解 Matplotlib 双 API 路径(pyplot 状态机 vs. OO 层级)在文档测试中的差异;
  2. 能否在跨后端、无显示设备的 CI 环境里让用例稳定通过;
  3. 是否熟悉项目自带的 matplotlib.testing 工具链,能屏蔽像素级噪声,避免 doctest 因抗锯齿差异随机失败。

一句话:面试官想看你在30 万行遗产代码里,如何写出一行既教学又回归的 doctest,还不破坏现有测试流水线。

知识点

  1. doctest 运行器选择:Matplotlib 主仓库不用标准 doctest,而用 matplotlib._docstring.doctest 包装器,自动注入 plt.ioff()、matplotlib.use('Agg') 等无头后端,避免 X11/MAC 报错。
  2. 输出抑制技巧:>>> plt.show() 会阻塞,必须用 # doctest: +SKIP;若需验证图像文件生成,用 >>> plt.savefig('/tmp/test.png') # doctest: +ELLIPSIS。
  3. 数值随机性:numpy.random 数据需加 np.random.seed(42),并在 docstring 里显式写出,否则不同机器灰度值差异导致像素测试失败。
  4. Artist 属性比对:推荐用 >>> np.testing.assert_allclose(line.get_xydata(), expected, rtol=1e-3) 替代肉眼坐标,既保留教学意义,又满足回归测试精度。
  5. PEP8 与 numpydoc 兼容性:doctest 代码块必须缩进 4 空格,与文档字符串 Examples 段落对齐;若参数列表已用 **kwargs,示例里不得出现未解释的关键字,否则 Code Review 会被打回。

答案

以 matplotlib.axes.Axes.fill_between 为例,展示一段可直接合入主干的 docstring doctest:

def fill_between(self, x, y1, y2=0, where=None, **kwargs):
    """
    Fill the area between two horizontal curves.

    Parameters
    ----------
    x : array-like, length N
    y1 : array-like, length N
    y2 : array-like, length N, default: 0
    where : array-like, length N, optional
        If *where* is provided, it specifies which positions to exclude.

    Returns
    -------
    `~matplotlib.collections.PolyCollection`
        The filled area.

    Examples
    --------
    **Basic usage (Agg backend automatically set by test runner):**

    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> np.random.seed(0)
    >>> x = np.linspace(0, 10, 200)
    >>> y1 = np.sin(x)
    >>> y2 = np.sin(x) + 0.3
    >>> fig, ax = plt.subplots()
    >>> poly = ax.fill_between(x, y1, y2, alpha=0.4)
    >>> ax.get_ylim()
    (-1.3, 1.3)
    >>> plt.close(fig)  # clean up memory

    **Exclude regions with *where*:**

    >>> fig, ax = plt.subplots()
    >>> cond = y1 > 0
    >>> poly = ax.fill_between(x, y1, y2, where=cond, color='g')
    >>> len(poly.get_paths())
    52
    >>> plt.close(fig)
    """

要点复盘:

  • 不调用 plt.show(),用 plt.close(fig) 防止内存泄漏;
  • 用 ax.get_ylim()、len(poly.get_paths()) 等确定性断言替代图像像素比对;
  • 显式设置随机种子,保证跨平台一致;
  • 所有绘图命令位于 Examples 段落,符合 numpydoc 规范,CI 里 python -m matplotlib.testing.doctest <module> 可零配置执行。

拓展思考

  1. 交互式后端下的 doctest:如果示例必须展示 jupyter-widget 交互,国内常见做法是拆成两行:
    >>> # doctest: +SKIP
    >>> ipywidgets.interact(update_plot, alpha=(0, 1, 0.1))
    并在文档中说明“本地 JupyterLab 运行效果”,既保留教学价值,又避免 CI 无 IPython kernel 时崩溃。

  2. 多语言 docstring:部分国企项目要求中英双语,doctest 只需保留一份,注释用中文即可;但断言输出必须英文,否则 pytest --doctest-modules 会因 locale 差异匹配失败。

  3. 性能红线:Matplotlib 核心 PR 要求 doctest 运行时间 < 300 ms。若示例需 1e6 点数据,务必用 >>> x = np.linspace(0, 1, 100_000) # doctest: +SKIP 并提示“实际生产可放大”,防止 GitHub Action 超时。

  4. 未来趋势:Matplotlib 3.9+ 正试点 matplotlib.testing.doctest-mpl 插件,支持 >>> plt.savefig('test.png') # doctest: +IMAGE 做像素级回归。提前阅读源码,理解 mpl-image-compare 阈值配置,能在面试中抛出**“如何用 0.001 RMS 容忍度做 doctest 图像比对”**的见解,直接拉满技术深度分。