← 中文资源

简体中文版本

warnings.catch_warnings 捕获告警

用 warnings.catch_warnings 发出并捕获告警,通过过滤器升级为异常,并查看记录的类别与消息。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

captured: 1
category: DeprecationWarning
message: legacy config key will be removed
promoted to error: legacy config key will be removed

实现说明

全部逻辑都在函数 load_config、main中。 为结果新分配了一个值;入参原样保留。

使用要点

  • 跑完文件,输出里会留下标记——captured:、category:、message:。
  • main 的演示流程是 load_config——跑一遍文件,这条流程从头到尾可见。

常见问题

load_config 会修改传入的参数吗?

不会。传入的任何东西都不会被写入,对共享数据调用是安全的。

运行「warnings.catch_warnings 捕获告警」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 captured:、category:、message: 标签标明各步骤。

入口签名:def load_config(legacy: bool) -> dict[str, str]

核心语句

return {"legacy": str(legacy).lower()}
with warnings.catch_warnings(record=True) as captured:
    warnings.simplefilter("always")
    load_config(legacy=True)
    load_config(legacy=False)
except DeprecationWarning as error:
    print("promoted to error:", error)

代码示例

import warnings


def load_config(legacy: bool) -> dict[str, str]:
    if legacy:
        warnings.warn(
            "legacy config key will be removed",
            DeprecationWarning,
            stacklevel=2,
        )
    return {"legacy": str(legacy).lower()}


def main() -> None:
    with warnings.catch_warnings(record=True) as captured:
        warnings.simplefilter("always")
        load_config(legacy=True)
        load_config(legacy=False)

    print("captured:", len(captured))
    print("category:", captured[0].category.__name__)
    print("message:", captured[0].message)

    with warnings.catch_warnings():
        warnings.simplefilter("error")
        try:
            load_config(legacy=True)
        except DeprecationWarning as error:
            print("promoted to error:", error)


if __name__ == "__main__":
    main()