NumPy参考 >例行程序 >Test Support (numpy.testing) > numpy.testing.suppress_warnings
numpy.testing.
suppress_warnings
(forward_rule ='always' )[源代码] ¶上下文管理器和装饰器的作用与相同
warnings.catch_warnings
。
但是,它也提供了一种过滤器机制来解决 https://bugs.python.org/issue4180的问题。
此错误导致3.4之前的Python在一次被忽略之后(即使在catch_warnings中)也无法可靠地再次显示警告。这意味着无法轻易使用“忽略”过滤器,因为后续测试可能需要查看警告。此外,它还可以简化测试警告的特异性,并且可以嵌套。
“总是”,“一次”,“模块”或“位置”之一。与通常的警告模块过滤器模式类似,主要在最外层降低噪声很有用。未抑制和未记录的警告将根据此规则转发。默认为“始终”。“位置”等同于警告“默认”,通过警告警告的确切位置进行匹配。
笔记
在上下文管理器中添加的过滤器在离开时将再次被丢弃。输入所有在外部定义的过滤器后,将自动应用。
添加记录过滤器后,匹配的警告将存储在
log
属性以及所返回的列表中record
。
If filters are added and the module
keyword is given, the
warning registry of this module will additionally be cleared when
applying it, entering the context, or exiting it. This could cause
warnings to appear a second time after leaving the context if they
were configured to be printed once (default) and were already
printed before the context was entered.
Nesting this context manager will work as expected when the forwarding rule is “always” (default). Unfiltered and unrecorded warnings will be passed out and be matched by the outer level. On the outmost level they will be printed (or caught by another warnings context). The forwarding rule argument can modify this behaviour.
Like catch_warnings
this context manager is not threadsafe.
Examples
With a context manager:
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
Or as a decorator:
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
Methods
|
函数装饰器,将某些抑制应用于整个函数。 |
|
添加新的抑制过滤器,或在进入状态后应用它。 |
|
附加一个新的记录过滤器,或在进入状态时应用它。 |