首页 > 解决方案 > Numpy 的 filterwarning 设置为忽略不会关闭警告,Python 的警告过滤器仍然会捕获它们

问题描述

从 Numpy 1.19 开始,在不显式调用的情况下创建一个参差不齐的数组dtype=object会引发 a VisibleDeprecationWarning,即

VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. If you meant to do this, you must specify 'dtype=object' when creating the ndarray

用 来关闭它们很容易np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning),但在我的情况下,我发现另一个包装UserWarning错误是为了用它做一些事情。问题是,这样做(在我的情况下是warnings.simplefilter("error", category=UserWarning))使得 numpy 警告不会被忽略,而是也会被提出。这是一个错误吗?我知道 numpy 警告是UserWarning(isinstance(np.VisibleDeprecationWarning(), UserWarning)评估为True) 的一个实例,但我本来希望根本不会引发警告。

下面是重现该行为的最小工作示例。warnings.simplefilter("error", category=UserWarning)可以注释掉以查看预期结果,其中'Be warned'作为警告引发并且忽略 numpy 警告。

import warnings
import numpy as np

np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning)
with warnings.catch_warnings() as w:
    warnings.simplefilter("error", category=UserWarning)
    try:        
        np.array([1,[1,2]]) # this raises np.VisibleDeprecationWarning
        warnings.warn('Be warned')
    except UserWarning as w:
        print('Warning was warned')
        warnings.warn(w)  # raises np.VisibleDeprecationWarning intead of UserWarning

标签: python-3.xnumpywarnings

解决方案


推荐阅读