实现说明
全部逻辑都在函数 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()