Numpy clobber functions my inherited data type

Let's say I have a class ndarray_plusthat inherits from numpy.ndarrayand adds some additional features. Sometimes I pass it to numpy functions such as np.sum, and returns an object of type ndarray_plus, as expected.

In other cases, the numpy functions that I pass to my extended object return an object numpy.ndarray, destroying the information in additional attributes ndarray_plus. This usually happens when the numpy function has a value np.asarrayinstead np.asanyarray.

Is there any way to prevent this? I cannot enter numpy codebase and change all instances np.asarrayto np.asanyarray. Is there a Pythonic way to proactively protect my inherited object?

+4
source share
1 answer

The specific and guaranteed behavior asarrayis to convert your instance of the subclass back to the base class

help on function asarray in numpy:

numpy.asarray = asarray(a, dtype=None, order=None)
Convert the input to an array.

Parameters
----------
a : array_like
    Input data, in any form that can be converted to an array.  This
    includes lists, lists of tuples, tuples, tuples of tuples, tuples
    of lists and ndarrays.
dtype : data-type, optional
    By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
    Whether to use row-major (C-style) or
    column-major (Fortran-style) memory representation.
    Defaults to 'C'.

Returns
-------
out : ndarray
    Array interpretation of `a`.  No copy is performed if the input
    is already an ndarray.  If `a` is a subclass of ndarray, a base
    class ndarray is returned.

See Also
--------
asanyarray : Similar function which passes through subclasses.

<- snip →

You can try monkeypatch too:

>>> import numpy as np
>>> import mpt
>>> 
>>> s = np.matrix(3)
>>> mpt.aa(s)
array([[3]])
>>> np.asarray = np.asanyarray
>>> mpt.aa(s)
matrix([[3]])

file mpt.py

import numpy as np

def aa(x):
   return np.asarray(x)

Unfortunately, this does not always work.

alternative mpt.py

from numpy import asarray

def aa(x):
   return asarray(x)

you're out of luck here.

0
source

Source: https://habr.com/ru/post/1669215/


All Articles