Numpy's filterwarning set to ignore doesn't turn warnings off and Python's warning filter still catches them

Viewed 291

Since Numpy 1.19, creating a ragged array without explicitly calling dtype=object raises a VisibleDeprecationWarning, namely

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

It's easy enough to turn them off with np.warnings.filterwarnings('ignore', category=np.VisibleDeprecationWarning), but in my case, I'm catching another packege's UserWarning as error to do some stuff with it. The issue is, doing this (in my case with warnings.simplefilter("error", category=UserWarning)) makes it so that the numpy warning is not ignored but rather raised too. Is this a bug? I understand that the numpy warning is an instance of UserWarning (isinstance(np.VisibleDeprecationWarning(), UserWarning) evaluates to True), but I would have expected the warning not be raised at all.

Below is a minimal working example to reproduce the behaviour. warnings.simplefilter("error", category=UserWarning) can be commented out to see the expected outcome, where 'Be warned' is raised as a warning and the numpy warning is ignored.

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
0 Answers
Related