如何标记弃用警告并记录到 rst?

解读

在国内 Matplotlib 岗位面试中,这道题考察的是**“代码演进与文档一致性”**的工程素养。
面试官想确认你能否:

  1. 用标准 Python 机制发出用户可见的弃用警告;
  2. 把同一信息同步写进开发者文档(rst),避免用户与文档说法不一;
  3. 熟悉 Matplotlib 双模式 API 下不同层级的弃用策略,保证 1.5 亿次年下载量的生态平稳过渡。
    答不到“rst 同步”环节,会被认为缺少开源社区协同经验;答不出“版本号控制”则视为对**语义化版本规范(SemVer)**理解不足。

知识点

  • warnings 模块:Python 标准库,提供 warn、filterwarnings、DeprecationWarning。
  • matplotlib._api.deprecation 子模块:Matplotlib 内部封装,支持since、removal、alternative 三个关键字,自动拼接统一格式的警告文本。
  • since 与 removal 版本号:必须遵循**“since=3.7.0, removal=3.9.0”** 这种双位或三位语义化版本,方便后续 CI 自动扫描。
  • rst 文档标记:Sphinx 指令 .. deprecated:: 3.7.0 与 .. versionchanged::,需放在 docstring 的 Notes 或 Warns 段落前,确保生成 html 时高亮。
  • pytest.warns:2000+ 单元测试中必须出现,TDD 先写测试再写功能,防止警告回归。
  • PEP 387 向后兼容策略:国内大厂二次发行版(如 Conda Forge、清华镜像)要求至少两个 minor 版本过渡期,否则会被打上“兼容性差评”标签。

答案

  1. 代码层标记
    在 matplotlib 内部,优先使用matplotlib._api.deprecation 而不是裸 warnings,示例:

    from matplotlib._api.deprecation import deprecated
    
    @deprecated(since="3.7.0", removal="3.9.0",
                alternative="axes.plot_date")
    def ax_plotxf(self, *args, **kwargs):
        ...
    

    如果是参数弃用,则:

    if old_param is not None:
        _api.warn_deprecated(
            since="3.7.0", removal="3.9.0",
            name="old_param", obj_type="parameter",
            alternative="new_param"
        )
    
  2. 文档层记录
    在同一函数的 docstring 顶部添加:

    .. deprecated:: 3.7.0
       ``ax_plotxf`` 将在 3.9.0 移除,请使用 :meth:`axes.plot_date`。
    

    若仅参数弃用,则在 Parameters 段落下写:

    old_param : str, optional
        .. deprecated:: 3.7.0
           使用 `new_param` 替代。
    
  3. 测试层兜底
    在 lib/matplotlib/tests/test_deprecation.py 新增:

    def test_ax_plotxf_deprecated():
        fig, ax = plt.subplots()
        with pytest.warns(mpl.MatplotlibDeprecationWarning,
                          match="ax_plotxf.*deprecated"):
            ax.plotxf([1, 2], [3, 4])
    

    保证后续 CI 若误删警告会立即红灯。

  4. 版本控制与 cherry-pick
    把上述改动做成独立 commit,标题写:

    DEP: deprecate ax_plotxf in favor of plot_date
    

    合并到 main 后,再 cherry-pick 到 v3.7.x 维护分支,确保国内源同步。

拓展思考

  • 自动化扫描:可写 pre-commit 脚本,正则匹配 .. deprecated:: 与 @deprecated 是否成对出现,防止“代码警告了但文档没写”或反之;该脚本已被华为 MindSpore 团队借鉴。
  • 多语言提示:若面向 Jupyter 中文用户,可在 warn_deprecated 中新增 message_zh 字段,动态检测 locale,实现中英双语警告,提升国内教育场景体验。
  • GPU 后端弃用:当弃用 WebGL 后端的某段 GL 着色器时,需在C++ 扩展里调用 PyErr_WarnFormat,并在 src/_backend_agg.cpp 的注释顶部补 .. deprecated::,保证渲染流水线与文档同步,避免像素级差异导致出版级图片异常。