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 內)。這表示無法輕易地使用 “ignore” 篩選器,因為後續的測試可能需要看到該警告。此外,它允許更輕鬆地指定測試警告,並且可以巢狀使用。

參數:
forwarding_rulestr,可選

“always”、“once”、“module” 或 “location” 之一。 類似於常用的 warnings 模組篩選模式,它有助於減少最外層的雜訊。未抑制和未記錄的警告將根據此規則轉發。預設為 “always”。“location” 等同於 warnings 的 “default”,依警告發生的確切位置進行比對。

註解

在上下文管理器內新增的篩選器,在離開時會再次捨棄。進入時,將自動套用在上下文之外定義的所有篩選器。

當新增記錄篩選器時,符合的警告會儲存在 log 屬性中,以及由 record 傳回的清單中。

如果新增了篩選器,並且給定了 module 關鍵字,則在套用、進入上下文或離開上下文時,還會清除此模組的警告註冊表。如果警告被設定為列印一次(預設),並且在進入上下文之前已經列印過,這可能會導致警告在離開上下文後再次出現。

當轉發規則為 “always”(預設)時,巢狀使用此上下文管理器將如預期般運作。未篩選和未記錄的警告將傳遞出去,並由外層比對。在最外層,它們將被列印(或被另一個 warnings 上下文捕獲)。forwarding_rule 參數可以修改此行為。

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])

附加新的記錄篩選器,或在狀態進入時套用它。