python-3.x - 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
解决方案
推荐阅读
- css - 在桌面上查看时,我一直试图放大我们网站的徽标,但似乎没有代码有效。我尝试了不同的版本,但失败了
- c++ - Arduino Nano nRF24L01 未读取消息
- c - OSX上的C Makefile冲突类型错误
- sql - 当java类有子类(jsonb)时,通过在JSONB上应用过滤器来查询postgresql中的数据
- csv - 将温度 csv 文件转换为 tiff
- mysql - kafka jdbc sink 连接器创建无效的数据类型
- python - 使用 pandas 根据指定的频率计算 pct_change
- android - 如何使用 MultiChoiceItems 获取选定的文本,而不是其在 AlertDialog 中的位置
- c# - 我是否在 Quartz.net 中设置了错误的工作?
- python - Python改变变量的引用