Standard array subclasses


Subclassing a numpy.ndarray is possible but if your goal is to create an array with modified behavior, as do dask arrays for distributed computation and cupy arrays for GPU-based computation, subclassing is discouraged. Instead, using numpy’s dispatch mechanism is recommended.



Special attributes and methods

NumPy provides several hooks that classes can customize:

class.__array_ufunc__(ufunc, method, *inputs, **kwargs)

New in version 1.13.


  • ufunc is the ufunc object that was called.


  • inputs is a tuple of the input arguments to the ufunc.

  • kwargs is a dictionary containing the optional input arguments of the ufunc. If given, any out arguments, both positional and keyword, are passed as a tuple in kwargs. See the discussion in Universal functions (ufunc) for details.


If one of the input or output arguments has a __array_ufunc__ method, it is executed instead of the ufunc. If more than one of the arguments implements __array_ufunc__, they are tried in the order: subclasses before superclasses, inputs before outputs, otherwise left to right. The first routine returning something other than NotImplemented determines the result. If all of the __array_ufunc__ operations return NotImplemented, a TypeError is raised.


We intend to re-implement numpy functions as (generalized) Ufunc, in which case it will become possible for them to be overridden by the __array_ufunc__ method. A prime candidate is matmul, which currently is not a Ufunc, but could be relatively easily be rewritten as a (set of) generalized Ufuncs. The same may happen with functions such as median, amin, and argsort.

Like with some other special methods in python, such as __hash__ and __iter__, it is possible to indicate that your class does not support ufuncs by setting __array_ufunc__ = None. Ufuncs always raise TypeError when called on an object that sets __array_ufunc__ = None.

The presence of __array_ufunc__ also influences how ndarray handles binary operations like arr + obj and arr < obj when arr is an ndarray and obj is an instance of a custom class. There are two possibilities. If obj.__array_ufunc__ is present and not None, then ndarray.__add__ and friends will delegate to the ufunc machinery, meaning that arr + obj becomes np.add(arr, obj), and then add invokes obj.__array_ufunc__. This is useful if you want to define an object that acts like an array.

Alternatively, if obj.__array_ufunc__ is set to None, then as a special case, special methods like ndarray.__add__ will notice this and unconditionally raise TypeError. This is useful if you want to create objects that interact with arrays via binary operations, but are not themselves arrays. For example, a units handling system might have an object m representing the “meters” unit, and want to support the syntax arr * m to represent that the array has units of “meters”, but not want to otherwise interact with arrays via ufuncs or otherwise. This can be done by setting __array_ufunc__ = None and defining __mul__ and __rmul__ methods. (Note that this means that writing an __array_ufunc__ that always returns NotImplemented is not quite the same as setting __array_ufunc__ = None: in the former case, arr + obj will raise TypeError, while in the latter case it is possible to define a __radd__ method to prevent this.)

The above does not hold for in-place operators, for which ndarray never returns NotImplemented. Hence, arr += obj would always lead to a TypeError. This is because for arrays in-place operations cannot generically be replaced by a simple reverse operation. (For instance, by default, arr += obj would be translated to arr = arr + obj, i.e., arr would be replaced, contrary to what is expected for in-place array operations.)


If you define __array_ufunc__:

  • If you are not a subclass of ndarray, we recommend your class define special methods like __add__ and __lt__ that delegate to ufuncs just like ndarray does. An easy way to do this is to subclass from NDArrayOperatorsMixin.

  • If you subclass ndarray, we recommend that you put all your override logic in __array_ufunc__ and not also override special methods. This ensures the class hierarchy is determined in only one place rather than separately by the ufunc machinery and by the binary operation rules (which gives preference to special methods of subclasses; the alternative way to enforce a one-place only hierarchy, of setting __array_ufunc__ to None, would seem very unexpected and thus confusing, as then the subclass would not work at all with ufuncs).

  • ndarray defines its own __array_ufunc__, which, evaluates the ufunc if no arguments have overrides, and returns NotImplemented otherwise. This may be useful for subclasses for which __array_ufunc__ converts any instances of its own class to ndarray: it can then pass these on to its superclass using super().__array_ufunc__(*inputs, **kwargs), and finally return the results after possible back-conversion. The advantage of this practice is that it ensures that it is possible to have a hierarchy of subclasses that extend the behaviour. See Subclassing ndarray for details.


If a class defines the __array_ufunc__ method, this disables the __array_wrap__, __array_prepare__, __array_priority__ mechanism described below for ufuncs (which may eventually be deprecated).

class.__array_function__(func, types, args, kwargs)

New in version 1.16.


  • In NumPy 1.17, the protocol is enabled by default, but can be disabled with NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=0.

  • In NumPy 1.16, you need to set the environment variable NUMPY_EXPERIMENTAL_ARRAY_FUNCTION=1 before importing NumPy to use NumPy function overrides.

  • Eventually, expect to __array_function__ to always be enabled.




As a convenience for __array_function__ implementors, types provides all argument types with an '__array_function__' attribute. This allows implementors to quickly identify cases where they should defer to __array_function__ implementations on other arguments. Implementations should not rely on the iteration order of types.

Most implementations of __array_function__ will start with two checks:







class MyArray:
        if func not in HANDLED_FUNCTIONS:
            return NotImplemented
        # Note: this allows subclasses that don't override
        # __array_function__ to handle MyArray objects
            return NotImplemented

def implements(numpy_function):
    def decorator(func):
        HANDLED_FUNCTIONS[numpy_function] = func
        return func
    return decorator

    ...  # implementation of concatenate for MyArray objects

def broadcast_to(array, shape):
    ...  # implementation of broadcast_to for MyArray objects


Just like the case for builtin special methods like __add__, properly written __array_function__ methods should always return NotImplemented when an unknown type is encountered. Otherwise, it will be impossible to correctly override NumPy functions from another object if the operation also includes one of your objects.

For the most part, the rules for dispatch with __array_function__ match those for __array_ufunc__. In particular:




If no __array_function__ methods exists, NumPy will default to calling its own implementation, intended for use on NumPy arrays. This case arises, for example, when all array-like arguments are Python numbers or lists. (NumPy arrays do have a __array_function__ method, given below, but it always returns NotImplemented if any argument other than a NumPy array subclass implements __array_function__.)




class.__array_prepare__(array, context=None)



For ufuncs, it is hoped to eventually deprecate this method in favour of __array_ufunc__.

class.__array_wrap__(array, context=None)










Matrix objects


It is strongly advised not to use the matrix subclass. As described below, it makes writing functions that deal consistently with matrices and regular arrays very difficult. Currently, they are mainly used for interacting with scipy.sparse. We hope to provide an alternative for this use, however, and eventually remove the matrix subclass.





  4. Matrix objects over-ride power to be matrix raised to a power. The same warning about using power inside a function that uses asanyarray(…) to get an array object holds for this fact.




    Returns the transpose of the matrix.


    Returns the (complex) conjugate transpose of self.


    Returns the (multiplicative) inverse of invertible self.


    Return self as an ndarray object.




matrix(data[, dtype, copy])


It is no longer recommended to use this class, even for linear

asmatrix(data[, dtype])

Interpret the input as a matrix.

bmat(obj[, ldict, gdict])


Example 1: Matrix creation from a string

>>> print (a*a.T).I
[[ 0.2924 -0.1345]
 [-0.1345  0.0819]]

Example 2: Matrix creation from nested sequence


Example 3: Matrix creation from an array

>>> mat(random.rand(3,3)).T
matrix([[ 0.7699,  0.7922,  0.3294],
        [ 0.2792,  0.0101,  0.9219],
        [ 0.3398,  0.7571,  0.8197]])

Memory-mapped file arrays






Write any changes in the array to the file on disk.


>>> a[10] = 10.0
>>> a[30] = 30.0
>>> del a
10.0 30.0
10.0 30.0

Character arrays (numpy.char)




chararray(shape[, itemsize, unicode, …])

Provides a convenient view on arrays of string and unicode values.

core.defchararray.array(obj[, itemsize, …])

Create a chararray.


Record arrays (numpy.rec)

NumPy provides the recarray class which allows accessing the fields of a structured array as attributes, and a corresponding scalar data type object record.


Construct an ndarray that allows field access using attributes.



Masked arrays (

See also

Masked arrays

Standard container class


numpy.lib.user_array.container(data[, …])

Standard container-class for easy multiple-inheritance.

Array Iterators


for val in myiter:
    some code involving val

calls val = next(myiter) repeatedly until StopIteration is raised by the iterator. There are several ways to iterate over an array that may be useful: default iteration, flat iteration, and N-dimensional enumeration.

Default iteration


for i in range(arr.shape[0]):
    val = arr[i]


>>> for val in a:
...     print 'item:', val
item: [[10 11 12 13]
 [14 15 16 17]]
item: [[18 19 20 21]
 [22 23 24 25]]
item: [[26 27 28 29]
 [30 31 32 33]]

Flat iteration


A 1-D iterator over the array.


0 10
5 15
10 20
15 25
20 30


N-dimensional enumeration


Multidimensional index iterator.


(0, 0, 0) 10
(1, 1, 3) 25
(2, 0, 3) 29
(2, 1, 2) 32

Iterator for broadcasting


Produce an object that mimics broadcasting.


...     print val
(1, 0)
(0, 1)
(2, 0)
(3, 1)