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, optional
“always”,“once”,“module” 或 “location” 之一.类似于通常的 warnings 模块过滤模式,它主要用于减少最外层的噪声.未抑制和未记录的警告将根据此规则转发.默认为“always”.“location” 等同于 warnings 的 “default”,按警告的确切位置进行匹配.
注释
在上下文管理器内部添加的过滤器将在离开时再次丢弃.进入时,将自动应用在上下文之外定义的所有过滤器.
当添加记录过滤器时,匹配的警告将存储在
log属性中,以及record返回的列表中.如果添加了过滤器并且给出了
module关键字,则在应用,进入或退出上下文时,还会清除此模块的警告注册表.如果警告被配置为打印一次(默认),并且在进入上下文之前已经打印过,这可能会导致警告在离开上下文后第二次出现.当转发规则为“always”(默认)时,嵌套此上下文管理器将按预期工作.未过滤和未记录的警告将被传递出去,并由外部级别匹配.在最外层,它们将被打印(或被另一个警告上下文捕获).转发规则参数可以修改此行为.
与
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
方法