numpy.testing.suppress_warnings#
- class numpy.testing.suppress_warnings(forwarding_rule='always')[源码]#
上下文管理器和装饰器,功能与
warnings.catch_warnings
大致相同。但是,它还提供了一种过滤机制,以解决 https://bugs.python.org/issue4180 中提到的问题。
这个错误导致 Python 3.4 之前的版本在警告被忽略一次(即使在 catch_warnings 中)后无法可靠地再次显示警告。这意味着无法轻易使用“忽略”过滤器,因为后续测试可能需要看到警告。此外,它允许更轻松地针对警告进行测试,并且可以嵌套。
- 参数:
- forwarding_rulestr, 可选
“always”、“once”、“module”或“location”之一。类似于常用的 warnings 模块过滤模式,主要用于减少最外层上的噪音。未抑制和未记录的警告将根据此规则转发。默认为“always”。“location”等同于 warnings 的“default”,按警告来源的精确位置进行匹配。
备注
在上下文管理器内添加的过滤器在离开时将被再次丢弃。进入时,在上下文外部定义的所有过滤器将自动应用。
添加记录过滤器后,匹配的警告将存储在
log
属性中,以及由record
返回的列表中。如果添加了过滤器并给定了
module
关键字,则此模块的警告注册表将在应用、进入上下文或退出上下文时额外被清除。如果警告被配置为打印一次(默认)并且在进入上下文之前已经打印过,这可能导致在离开上下文后警告再次出现。当转发规则为“always”(默认)时,嵌套此上下文管理器将按预期工作。未过滤和未记录的警告将被传递出去,并由外层匹配。在最外层,它们将被打印(或被另一个 warnings 上下文捕获)。转发规则参数可以修改此行为。
与
catch_warnings
一样,此上下文管理器不是线程安全的。示例
使用上下文管理器
with np.testing.suppress_warnings() as sup: sup.filter(DeprecationWarning, "Some text") sup.filter(module=np.ma.core) log = sup.record(FutureWarning, "Does this occur?") command_giving_warnings() # The FutureWarning was given once, the filtered warnings were # ignored. All other warnings abide outside settings (may be # printed/error) assert_(len(log) == 1) assert_(len(sup.log) == 1) # also stored in log attribute
或作为装饰器
sup = np.testing.suppress_warnings() sup.filter(module=np.ma.core) # module must match exactly @sup def some_function(): # do something which causes a warning in np.ma.core pass
方法