Closed
Description
Using warnings.filterwarnings
with a numpy wrapper class changes the behavior of np.asarray
(or rather np.array
).
I believe the reason for this is the equivalent of an except Exception
block (in the C code), since the warning base class Warning
inherits from Exception
.
Having __len__
and __getitem__
is not required to reproduce, but they make the difference a bit more obvious.
xref hgrecco/pint#892
Reproducing code example:
import warnings
import numpy as np
class NumpyWrapper:
def __init__(self, array):
self.array = array
def __len__(self):
return len(self.array)
def __getitem__(self, *args, **kwargs):
return type(self)(self.array.__getitem__(*args, **kwargs))
def __getattr__(self, name):
if name.startswith("__array_"):
warnings.warn("object got converted", UserWarning)
return getattr(self.array, name)
def __repr__(self):
return f"<Wrapper({self.array})>"
array = NumpyWrapper(np.arange(10))
print(repr(np.asarray(array)) # warning
# [0 1 2 3 4 5 6 7 8 9]
warnings.filterwarnings("error")
print(repr(np.asarray(array)) # no warning, but also no error
# [<Wrapper(0)> <Wrapper(1)> <Wrapper(2)> <Wrapper(3)> <Wrapper(4)>
# <Wrapper(5)> <Wrapper(6)> <Wrapper(7)> <Wrapper(8)> <Wrapper(9)>]
Numpy/Python version information:
numpy: 1.17.2
python: 3.7.3