numpy.testing.suppress_warnings#

class numpy.testing.suppress_warnings(forwarding_rule='always', _warn=True)[源代码]#

上下文管理器和装饰器,功能与 warnings.catch_warnings 大致相同。

然而,它还提供了一个过滤机制来解决 https://bugs.python.org/issue4180

此 bug 导致 Python 3.4 之前的版本在忽略警告一次后(即使在 catch_warnings 中)也无法可靠地再次显示警告。这意味着不能轻易使用“忽略”过滤器,因为后续测试可能需要看到该警告。此外,它允许更方便地针对性测试警告,并且可以嵌套使用。

自 2.4 版本起已弃用: 此功能已弃用。请改用 warnings.filterwarningspytest.filterwarnings

参数:
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

方法

__call__(func)

函数装饰器,用于将某些抑制应用于整个函数。

filter([category, message, module])

添加一个新的抑制过滤器,或在进入状态时应用它。

record([category, message, module])

添加一个新的记录过滤器,或在进入状态时应用它。