Array API#
Array structure and data access#
These macros access the PyArrayObject
structure members and are
defined in ndarraytypes.h
. The input argument, arr, can be any
PyObject* that is directly interpretable as a
PyArrayObject* (any instance of the PyArray_Type
and its subtypes).

int PyArray_NDIM(PyArrayObject *arr)#
The number of dimensions in the array.

int PyArray_FLAGS(PyArrayObject *arr)#
Returns an integer representing the arrayflags.

int PyArray_TYPE(PyArrayObject *arr)#
Return the (builtin) typenumber for the elements of this array.

int PyArray_SETITEM(PyArrayObject *arr, void *itemptr, PyObject *obj)#
Convert obj and place it in the ndarray, arr, at the place pointed to by itemptr. Return 1 if an error occurs or 0 on success.

void PyArray_ENABLEFLAGS(PyArrayObject *arr, int flags)#
New in version 1.7.
Enables the specified array flags. This function does no validation, and assumes that you know what you’re doing.

void PyArray_CLEARFLAGS(PyArrayObject *arr, int flags)#
New in version 1.7.
Clears the specified array flags. This function does no validation, and assumes that you know what you’re doing.

void *PyArray_DATA(PyArrayObject *arr)#

char *PyArray_BYTES(PyArrayObject *arr)#
These two macros are similar and obtain the pointer to the databuffer for the array. The first macro can (and should be) assigned to a particular pointer where the second is for generic processing. If you have not guaranteed a contiguous and/or aligned array then be sure you understand how to access the data in the array to avoid memory and/or alignment problems.

npy_intp *PyArray_DIMS(PyArrayObject *arr)#
Returns a pointer to the dimensions/shape of the array. The number of elements matches the number of dimensions of the array. Can return
NULL
for 0dimensional arrays.

npy_intp *PyArray_SHAPE(PyArrayObject *arr)#
New in version 1.7.
A synonym for
PyArray_DIMS
, named to be consistent with theshape
usage within Python.

npy_intp *PyArray_STRIDES(PyArrayObject *arr)#
Returns a pointer to the strides of the array. The number of elements matches the number of dimensions of the array.

npy_intp PyArray_DIM(PyArrayObject *arr, int n)#
Return the shape in the n \(^{\textrm{th}}\) dimension.

npy_intp PyArray_STRIDE(PyArrayObject *arr, int n)#
Return the stride in the n \(^{\textrm{th}}\) dimension.

npy_intp PyArray_ITEMSIZE(PyArrayObject *arr)#
Return the itemsize for the elements of this array.
Note that, in the old API that was deprecated in version 1.7, this function had the return type
int
.

npy_intp PyArray_SIZE(PyArrayObject *arr)#
Returns the total size (in number of elements) of the array.

npy_intp PyArray_Size(PyArrayObject *obj)#
Returns 0 if obj is not a subclass of ndarray. Otherwise, returns the total number of elements in the array. Safer version of
PyArray_SIZE
(obj).

npy_intp PyArray_NBYTES(PyArrayObject *arr)#
Returns the total number of bytes consumed by the array.

PyObject *PyArray_BASE(PyArrayObject *arr)#
This returns the base object of the array. In most cases, this means the object which owns the memory the array is pointing at.
If you are constructing an array using the C API, and specifying your own memory, you should use the function
PyArray_SetBaseObject
to set the base to an object which owns the memory.If the
NPY_ARRAY_WRITEBACKIFCOPY
flag is set, it has a different meaning, namely base is the array into which the current array will be copied upon copy resolution. This overloading of the base property for two functions is likely to change in a future version of NumPy.

PyArray_Descr *PyArray_DESCR(PyArrayObject *arr)#
Returns a borrowed reference to the dtype property of the array.

PyArray_Descr *PyArray_DTYPE(PyArrayObject *arr)#
New in version 1.7.
A synonym for PyArray_DESCR, named to be consistent with the ‘dtype’ usage within Python.

PyObject *PyArray_GETITEM(PyArrayObject *arr, void *itemptr)#
Get a Python object of a builtin type from the ndarray, arr, at the location pointed to by itemptr. Return
NULL
on failure.numpy.ndarray.item
is identical to PyArray_GETITEM.

int PyArray_FinalizeFunc(PyArrayObject *arr, PyObject *obj)#
The function pointed to by the
PyCapsule
__array_finalize__
. The first argument is the newly created subtype. The second argument (if not NULL) is the “parent” array (if the array was created using slicing or some other operation where a clearlydistinguishable parent is present). This routine can do anything it wants to. It should return a 1 on error and 0 otherwise.
Data access#
These functions and macros provide easy access to elements of the
ndarray from C. These work for all arrays. You may need to take care
when accessing the data in the array, however, if it is not in machine
byteorder, misaligned, or not writeable. In other words, be sure to
respect the state of the flags unless you know what you are doing, or
have previously guaranteed an array that is writeable, aligned, and in
machine byteorder using PyArray_FromAny
. If you wish to handle all
types of arrays, the copyswap function for each type is useful for
handling misbehaved arrays. Some platforms (e.g. Solaris) do not like
misaligned data and will crash if you dereference a misaligned
pointer. Other platforms (e.g. x86 Linux) will just work more slowly
with misaligned data.

void *PyArray_GetPtr(PyArrayObject *aobj, npy_intp *ind)#
Return a pointer to the data of the ndarray, aobj, at the Ndimensional index given by the carray, ind, (which must be at least aobj >nd in size). You may want to typecast the returned pointer to the data type of the ndarray.

void *PyArray_GETPTR1(PyArrayObject *obj, npy_intp i)#

void *PyArray_GETPTR2(PyArrayObject *obj, npy_intp i, npy_intp j)#

void *PyArray_GETPTR3(PyArrayObject *obj, npy_intp i, npy_intp j, npy_intp k)#

void *PyArray_GETPTR4(PyArrayObject *obj, npy_intp i, npy_intp j, npy_intp k, npy_intp l)#
Quick, inline access to the element at the given coordinates in the ndarray, obj, which must have respectively 1, 2, 3, or 4 dimensions (this is not checked). The corresponding i, j, k, and l coordinates can be any integer but will be interpreted as
npy_intp
. You may want to typecast the returned pointer to the data type of the ndarray.
Creating arrays#
From scratch#

PyObject *PyArray_NewFromDescr(PyTypeObject *subtype, PyArray_Descr *descr, int nd, npy_intp const *dims, npy_intp const *strides, void *data, int flags, PyObject *obj)#
This function steals a reference to descr. The easiest way to get one is using
PyArray_DescrFromType
.This is the main array creation function. Most new arrays are created with this flexible function.
The returned object is an object of Pythontype subtype, which must be a subtype of
PyArray_Type
. The array has nd dimensions, described by dims. The datatype descriptor of the new array is descr.If subtype is of an array subclass instead of the base
&PyArray_Type
, then obj is the object to pass to the__array_finalize__
method of the subclass.If data is
NULL
, then new unitinialized memory will be allocated and flags can be nonzero to indicate a Fortranstyle contiguous array. UsePyArray_FILLWBYTE
to initialize the memory.If data is not
NULL
, then it is assumed to point to the memory to be used for the array and the flags argument is used as the new flags for the array (except the state ofNPY_ARRAY_OWNDATA
,NPY_ARRAY_WRITEBACKIFCOPY
flag of the new array will be reset).In addition, if data is nonNULL, then strides can also be provided. If strides is
NULL
, then the array strides are computed as Cstyle contiguous (default) or Fortranstyle contiguous (flags is nonzero for data =NULL
or flags &NPY_ARRAY_F_CONTIGUOUS
is nonzero nonNULL data). Any provided dims and strides are copied into newly allocated dimension and strides arrays for the new array object.PyArray_CheckStrides
can help verify nonNULL
stride information.If
data
is provided, it must stay alive for the life of the array. One way to manage this is throughPyArray_SetBaseObject

PyObject *PyArray_NewLikeArray(PyArrayObject *prototype, NPY_ORDER order, PyArray_Descr *descr, int subok)#
New in version 1.6.
This function steals a reference to descr if it is not NULL. This array creation routine allows for the convenient creation of a new array matching an existing array’s shapes and memory layout, possibly changing the layout and/or data type.
When order is
NPY_ANYORDER
, the result order isNPY_FORTRANORDER
if prototype is a fortran array,NPY_CORDER
otherwise. When order isNPY_KEEPORDER
, the result order matches that of prototype, even when the axes of prototype aren’t in C or Fortran order.If descr is NULL, the data type of prototype is used.
If subok is 1, the newly created array will use the subtype of prototype to create the new array, otherwise it will create a baseclass array.

PyObject *PyArray_New(PyTypeObject *subtype, int nd, npy_intp const *dims, int type_num, npy_intp const *strides, void *data, int itemsize, int flags, PyObject *obj)#
This is similar to
PyArray_NewFromDescr
(…) except you specify the datatype descriptor with type_num and itemsize, where type_num corresponds to a builtin (or userdefined) type. If the type always has the same number of bytes, then itemsize is ignored. Otherwise, itemsize specifies the particular size of this array.
Warning
If data is passed to PyArray_NewFromDescr
or PyArray_New
,
this memory must not be deallocated until the new array is
deleted. If this data came from another Python object, this can
be accomplished using Py_INCREF
on that object and setting the
base member of the new array to point to that object. If strides
are passed in they must be consistent with the dimensions, the
itemsize, and the data of the array.

PyObject *PyArray_SimpleNew(int nd, npy_intp const *dims, int typenum)#
Create a new uninitialized array of type, typenum, whose size in each of nd dimensions is given by the integer array, dims.The memory for the array is uninitialized (unless typenum is
NPY_OBJECT
in which case each element in the array is set to NULL). The typenum argument allows specification of any of the builtin datatypes such asNPY_FLOAT
orNPY_LONG
. The memory for the array can be set to zero if desired usingPyArray_FILLWBYTE
(return_object, 0).This function cannot be used to create a flexibletype array (no itemsize given).

PyObject *PyArray_SimpleNewFromData(int nd, npy_intp const *dims, int typenum, void *data)#
Create an array wrapper around data pointed to by the given pointer. The array flags will have a default that the data area is wellbehaved and Cstyle contiguous. The shape of the array is given by the dims carray of length nd. The datatype of the array is indicated by typenum. If data comes from another referencecounted Python object, the reference count on this object should be increased after the pointer is passed in, and the base member of the returned ndarray should point to the Python object that owns the data. This will ensure that the provided memory is not freed while the returned array is in existence.

PyObject *PyArray_SimpleNewFromDescr(int nd, npy_int const *dims, PyArray_Descr *descr)#
This function steals a reference to descr.
Create a new array with the provided datatype descriptor, descr, of the shape determined by nd and dims.

void PyArray_FILLWBYTE(PyObject *obj, int val)#
Fill the array pointed to by obj —which must be a (subclass of) ndarray—with the contents of val (evaluated as a byte). This macro calls memset, so obj must be contiguous.

PyObject *PyArray_Zeros(int nd, npy_intp const *dims, PyArray_Descr *dtype, int fortran)#
Construct a new nd dimensional array with shape given by dims and data type given by dtype. If fortran is nonzero, then a Fortranorder array is created, otherwise a Corder array is created. Fill the memory with zeros (or the 0 object if dtype corresponds to
NPY_OBJECT
).

PyObject *PyArray_ZEROS(int nd, npy_intp const *dims, int type_num, int fortran)#
Macro form of
PyArray_Zeros
which takes a typenumber instead of a datatype object.

PyObject *PyArray_Empty(int nd, npy_intp const *dims, PyArray_Descr *dtype, int fortran)#
Construct a new nd dimensional array with shape given by dims and data type given by dtype. If fortran is nonzero, then a Fortranorder array is created, otherwise a Corder array is created. The array is uninitialized unless the data type corresponds to
NPY_OBJECT
in which case the array is filled withPy_None
.

PyObject *PyArray_EMPTY(int nd, npy_intp const *dims, int typenum, int fortran)#
Macro form of
PyArray_Empty
which takes a typenumber, typenum, instead of a datatype object.

PyObject *PyArray_Arange(double start, double stop, double step, int typenum)#
Construct a new 1dimensional array of datatype, typenum, that ranges from start to stop (exclusive) in increments of step . Equivalent to arange (start, stop, step, dtype).

PyObject *PyArray_ArangeObj(PyObject *start, PyObject *stop, PyObject *step, PyArray_Descr *descr)#
Construct a new 1dimensional array of datatype determined by
descr
, that ranges fromstart
tostop
(exclusive) in increments ofstep
. Equivalent to arange(start
,stop
,step
,typenum
).

int PyArray_SetBaseObject(PyArrayObject *arr, PyObject *obj)#
New in version 1.7.
This function steals a reference to
obj
and sets it as the base property ofarr
.If you construct an array by passing in your own memory buffer as a parameter, you need to set the array’s base property to ensure the lifetime of the memory buffer is appropriate.
The return value is 0 on success, 1 on failure.
If the object provided is an array, this function traverses the chain of base pointers so that each array points to the owner of the memory directly. Once the base is set, it may not be changed to another value.
From other objects#

PyObject *PyArray_FromAny(PyObject *op, PyArray_Descr *dtype, int min_depth, int max_depth, int requirements, PyObject *context)#
This is the main function used to obtain an array from any nested sequence, or object that exposes the array interface, op. The parameters allow specification of the required dtype, the minimum (min_depth) and maximum (max_depth) number of dimensions acceptable, and other requirements for the array. This function steals a reference to the dtype argument, which needs to be a
PyArray_Descr
structure indicating the desired datatype (including required byteorder). The dtype argument may beNULL
, indicating that any datatype (and byteorder) is acceptable. UnlessNPY_ARRAY_FORCECAST
is present inflags
, this call will generate an error if the data type cannot be safely obtained from the object. If you want to useNULL
for the dtype and ensure the array is not swapped then usePyArray_CheckFromAny
. A value of 0 for either of the depth parameters causes the parameter to be ignored. Any of the following array flags can be added (e.g. using ) to get the requirements argument. If your code can handle general (e.g. strided, byteswapped, or unaligned arrays) then requirements may be 0. Also, if op is not already an array (or does not expose the array interface), then a new array will be created (and filled from op using the sequence protocol). The new array will haveNPY_ARRAY_DEFAULT
as its flags member. The context argument is unused.NPY_ARRAY_C_CONTIGUOUS
Make sure the returned array is Cstyle contiguous
NPY_ARRAY_F_CONTIGUOUS
Make sure the returned array is Fortranstyle contiguous.
NPY_ARRAY_ALIGNED
Make sure the returned array is aligned on proper boundaries for its data type. An aligned array has the data pointer and every strides factor as a multiple of the alignment factor for the datatype descriptor.
NPY_ARRAY_WRITEABLE
Make sure the returned array can be written to.
NPY_ARRAY_ENSURECOPY
Make sure a copy is made of op. If this flag is not present, data is not copied if it can be avoided.
NPY_ARRAY_ENSUREARRAY
Make sure the result is a baseclass ndarray. By default, if op is an instance of a subclass of ndarray, an instance of that same subclass is returned. If this flag is set, an ndarray object will be returned instead.
NPY_ARRAY_FORCECAST
Force a cast to the output type even if it cannot be done safely. Without this flag, a data cast will occur only if it can be done safely, otherwise an error is raised.
NPY_ARRAY_WRITEBACKIFCOPY
If op is already an array, but does not satisfy the requirements, then a copy is made (which will satisfy the requirements). If this flag is present and a copy (of an object that is already an array) must be made, then the corresponding
NPY_ARRAY_WRITEBACKIFCOPY
flag is set in the returned copy and op is made to be readonly. You must be sure to callPyArray_ResolveWritebackIfCopy
to copy the contents back into op and the op array will be made writeable again. If op is not writeable to begin with, or if it is not already an array, then an error is raised.
Combinations of array flags can also be added.

PyObject *PyArray_CheckFromAny(PyObject *op, PyArray_Descr *dtype, int min_depth, int max_depth, int requirements, PyObject *context)#
Nearly identical to
PyArray_FromAny
(…) except requirements can containNPY_ARRAY_NOTSWAPPED
(overriding the specification in dtype) andNPY_ARRAY_ELEMENTSTRIDES
which indicates that the array should be aligned in the sense that the strides are multiples of the element size.

PyObject *PyArray_FromArray(PyArrayObject *op, PyArray_Descr *newtype, int requirements)#
Special case of
PyArray_FromAny
for when op is already an array but it needs to be of a specific newtype (including byteorder) or has certain requirements.

PyObject *PyArray_FromStructInterface(PyObject *op)#
Returns an ndarray object from a Python object that exposes the
__array_struct__
attribute and follows the array interface protocol. If the object does not contain this attribute then a borrowed reference toPy_NotImplemented
is returned.

PyObject *PyArray_FromInterface(PyObject *op)#
Returns an ndarray object from a Python object that exposes the
__array_interface__
attribute following the array interface protocol. If the object does not contain this attribute then a borrowed reference toPy_NotImplemented
is returned.

PyObject *PyArray_FromArrayAttr(PyObject *op, PyArray_Descr *dtype, PyObject *context)#
Return an ndarray object from a Python object that exposes the
__array__
method. The thirdparty implementations of__array__
must takedtype
andcopy
keyword arguments.context
is unused.

PyObject *PyArray_ContiguousFromAny(PyObject *op, int typenum, int min_depth, int max_depth)#
This function returns a (Cstyle) contiguous and behaved function array from any nested sequence or array interface exporting object, op, of (nonflexible) type given by the enumerated typenum, of minimum depth min_depth, and of maximum depth max_depth. Equivalent to a call to
PyArray_FromAny
with requirements set toNPY_ARRAY_DEFAULT
and the type_num member of the type argument set to typenum.

PyObject *PyArray_ContiguousFromObject(PyObject *op, int typenum, int min_depth, int max_depth)#
This function returns a wellbehaved Cstyle contiguous array from any nested sequence or arrayinterface exporting object. The minimum number of dimensions the array can have is given by min_depth while the maximum is max_depth. This is equivalent to call
PyArray_FromAny
with requirementsNPY_ARRAY_DEFAULT
andNPY_ARRAY_ENSUREARRAY
.

PyObject *PyArray_FromObject(PyObject *op, int typenum, int min_depth, int max_depth)#
Return an aligned and in nativebyteorder array from any nested sequence or arrayinterface exporting object, op, of a type given by the enumerated typenum. The minimum number of dimensions the array can have is given by min_depth while the maximum is max_depth. This is equivalent to a call to
PyArray_FromAny
with requirements set to BEHAVED.

PyObject *PyArray_EnsureArray(PyObject *op)#
This function steals a reference to
op
and makes sure thatop
is a baseclass ndarray. It special cases array scalars, but otherwise callsPyArray_FromAny
(op
, NULL, 0, 0,NPY_ARRAY_ENSUREARRAY
, NULL).

PyObject *PyArray_FromString(char *string, npy_intp slen, PyArray_Descr *dtype, npy_intp num, char *sep)#
Construct a onedimensional ndarray of a single type from a binary or (ASCII) text
string
of lengthslen
. The datatype of the array tobecreated is given bydtype
. If num is 1, then copy the entire string and return an appropriately sized array, otherwise,num
is the number of items to copy from the string. Ifsep
is NULL (or “”), then interpret the string as bytes of binary data, otherwise convert the substrings separated bysep
to items of datatypedtype
. Some datatypes may not be readable in text mode and an error will be raised if that occurs. All errors return NULL.

PyObject *PyArray_FromFile(FILE *fp, PyArray_Descr *dtype, npy_intp num, char *sep)#
Construct a onedimensional ndarray of a single type from a binary or text file. The open file pointer is
fp
, the datatype of the array to be created is given bydtype
. This must match the data in the file. Ifnum
is 1, then read until the end of the file and return an appropriately sized array, otherwise,num
is the number of items to read. Ifsep
is NULL (or “”), then read from the file in binary mode, otherwise read from the file in text mode withsep
providing the item separator. Some array types cannot be read in text mode in which case an error is raised.

PyObject *PyArray_FromBuffer(PyObject *buf, PyArray_Descr *dtype, npy_intp count, npy_intp offset)#
Construct a onedimensional ndarray of a single type from an object,
buf
, that exports the (singlesegment) buffer protocol (or has an attribute __buffer__ that returns an object that exports the buffer protocol). A writeable buffer will be tried first followed by a read only buffer. TheNPY_ARRAY_WRITEABLE
flag of the returned array will reflect which one was successful. The data is assumed to start atoffset
bytes from the start of the memory location for the object. The type of the data in the buffer will be interpreted depending on the data type descriptor,dtype.
Ifcount
is negative then it will be determined from the size of the buffer and the requested itemsize, otherwise,count
represents how many elements should be converted from the buffer.

int PyArray_CopyInto(PyArrayObject *dest, PyArrayObject *src)#
Copy from the source array,
src
, into the destination array,dest
, performing a datatype conversion if necessary. If an error occurs return 1 (otherwise 0). The shape ofsrc
must be broadcastable to the shape ofdest
. NumPy checks for overlapping memory when copying two arrays.

int PyArray_CopyObject(PyArrayObject *dest, PyObject *src)#
Assign an object
src
to a NumPy arraydest
according to arraycoercion rules. This is basically identical toPyArray_FromAny
, but assigns directly to the output array. Returns 0 on success and 1 on failures.

PyArrayObject *PyArray_GETCONTIGUOUS(PyObject *op)#
If
op
is already (Cstyle) contiguous and wellbehaved then just return a reference, otherwise return a (contiguous and wellbehaved) copy of the array. The parameter op must be a (subclass of an) ndarray and no checking for that is done.

PyObject *PyArray_FROM_O(PyObject *obj)#
Convert
obj
to an ndarray. The argument can be any nested sequence or object that exports the array interface. This is a macro form ofPyArray_FromAny
usingNULL
, 0, 0, 0 for the other arguments. Your code must be able to handle any datatype descriptor and any combination of dataflags to use this macro.

PyObject *PyArray_FROM_OF(PyObject *obj, int requirements)#
Similar to
PyArray_FROM_O
except it can take an argument of requirements indicating properties the resulting array must have. Available requirements that can be enforced areNPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_F_CONTIGUOUS
,NPY_ARRAY_ALIGNED
,NPY_ARRAY_WRITEABLE
,NPY_ARRAY_NOTSWAPPED
,NPY_ARRAY_ENSURECOPY
,NPY_ARRAY_WRITEBACKIFCOPY
,NPY_ARRAY_FORCECAST
, andNPY_ARRAY_ENSUREARRAY
. Standard combinations of flags can also be used:

PyObject *PyArray_FROM_OT(PyObject *obj, int typenum)#
Similar to
PyArray_FROM_O
except it can take an argument of typenum specifying the typenumber the returned array.

PyObject *PyArray_FROM_OTF(PyObject *obj, int typenum, int requirements)#
Combination of
PyArray_FROM_OF
andPyArray_FROM_OT
allowing both a typenum and a flags argument to be provided.

PyObject *PyArray_FROMANY(PyObject *obj, int typenum, int min, int max, int requirements)#
Similar to
PyArray_FromAny
except the datatype is specified using a typenumber.PyArray_DescrFromType
(typenum) is passed directly toPyArray_FromAny
. This macro also addsNPY_ARRAY_DEFAULT
to requirements ifNPY_ARRAY_ENSURECOPY
is passed in as requirements.

PyObject *PyArray_CheckAxis(PyObject *obj, int *axis, int requirements)#
Encapsulate the functionality of functions and methods that take the axis= keyword and work properly with None as the axis argument. The input array is
obj
, while*axis
is a converted integer (so that >=MAXDIMS is the None value), andrequirements
gives the needed properties ofobj
. The output is a converted version of the input so that requirements are met and if needed a flattening has occurred. On output negative values of*axis
are converted and the new value is checked to ensure consistency with the shape ofobj
.
Dealing with types#
General check of Python Type#

int PyArray_Check(PyObject *op)#
Evaluates true if op is a Python object whose type is a subtype of
PyArray_Type
.

int PyArray_CheckExact(PyObject *op)#
Evaluates true if op is a Python object with type
PyArray_Type
.

int PyArray_HasArrayInterface(PyObject *op, PyObject *out)#
If
op
implements any part of the array interface, thenout
will contain a new reference to the newly created ndarray using the interface orout
will containNULL
if an error during conversion occurs. Otherwise, out will contain a borrowed reference toPy_NotImplemented
and no error condition is set.

int PyArray_HasArrayInterfaceType(PyObject *op, PyArray_Descr *dtype, PyObject *context, PyObject *out)#
If
op
implements any part of the array interface, thenout
will contain a new reference to the newly created ndarray using the interface orout
will containNULL
if an error during conversion occurs. Otherwise, out will contain a borrowed reference to Py_NotImplemented and no error condition is set. This version allows setting of the dtype in the part of the array interface that looks for the__array__
attribute. context is unused.

int PyArray_IsZeroDim(PyObject *op)#
Evaluates true if op is an instance of (a subclass of)
PyArray_Type
and has 0 dimensions.

PyArray_IsScalar(op, cls)#
Evaluates true if op is an instance of
Py{cls}ArrType_Type
.

int PyArray_CheckScalar(PyObject *op)#
Evaluates true if op is either an array scalar (an instance of a subtype of
PyGenericArrType_Type
), or an instance of (a subclass of)PyArray_Type
whose dimensionality is 0.

int PyArray_IsPythonNumber(PyObject *op)#
Evaluates true if op is an instance of a builtin numeric type (int, float, complex, long, bool)

int PyArray_IsPythonScalar(PyObject *op)#
Evaluates true if op is a builtin Python scalar object (int, float, complex, bytes, str, long, bool).

int PyArray_IsAnyScalar(PyObject *op)#
Evaluates true if op is either a Python scalar object (see
PyArray_IsPythonScalar
) or an array scalar (an instance of a sub type ofPyGenericArrType_Type
).

int PyArray_CheckAnyScalar(PyObject *op)#
Evaluates true if op is a Python scalar object (see
PyArray_IsPythonScalar
), an array scalar (an instance of a subtype ofPyGenericArrType_Type
) or an instance of a subtype ofPyArray_Type
whose dimensionality is 0.
Datatype checking#
For the typenum macros, the argument is an integer representing an enumerated array data type. For the array type checking macros the argument must be a PyObject* that can be directly interpreted as a PyArrayObject*.

int PyTypeNum_ISUNSIGNED(int num)#

int PyDataType_ISUNSIGNED(PyArray_Descr *descr)#

int PyArray_ISUNSIGNED(PyArrayObject *obj)#
Type represents an unsigned integer.

int PyTypeNum_ISSIGNED(int num)#

int PyDataType_ISSIGNED(PyArray_Descr *descr)#

int PyArray_ISSIGNED(PyArrayObject *obj)#
Type represents a signed integer.

int PyTypeNum_ISINTEGER(int num)#

int PyDataType_ISINTEGER(PyArray_Descr *descr)#

int PyArray_ISINTEGER(PyArrayObject *obj)#
Type represents any integer.

int PyTypeNum_ISFLOAT(int num)#

int PyDataType_ISFLOAT(PyArray_Descr *descr)#

int PyArray_ISFLOAT(PyArrayObject *obj)#
Type represents any floating point number.

int PyTypeNum_ISCOMPLEX(int num)#

int PyDataType_ISCOMPLEX(PyArray_Descr *descr)#

int PyArray_ISCOMPLEX(PyArrayObject *obj)#
Type represents any complex floating point number.

int PyTypeNum_ISNUMBER(int num)#

int PyDataType_ISNUMBER(PyArray_Descr *descr)#

int PyArray_ISNUMBER(PyArrayObject *obj)#
Type represents any integer, floating point, or complex floating point number.

int PyTypeNum_ISSTRING(int num)#

int PyDataType_ISSTRING(PyArray_Descr *descr)#

int PyArray_ISSTRING(PyArrayObject *obj)#
Type represents a string data type.

int PyTypeNum_ISFLEXIBLE(int num)#

int PyDataType_ISFLEXIBLE(PyArray_Descr *descr)#

int PyArray_ISFLEXIBLE(PyArrayObject *obj)#
Type represents one of the flexible array types (
NPY_STRING
,NPY_UNICODE
, orNPY_VOID
).

int PyDataType_ISUNSIZED(PyArray_Descr *descr)#
Type has no size information attached, and can be resized. Should only be called on flexible dtypes. Types that are attached to an array will always be sized, hence the array form of this macro not existing.
Changed in version 1.18.
For structured datatypes with no fields this function now returns False.

int PyTypeNum_ISUSERDEF(int num)#

int PyDataType_ISUSERDEF(PyArray_Descr *descr)#

int PyArray_ISUSERDEF(PyArrayObject *obj)#
Type represents a userdefined type.

int PyTypeNum_ISEXTENDED(int num)#

int PyDataType_ISEXTENDED(PyArray_Descr *descr)#

int PyArray_ISEXTENDED(PyArrayObject *obj)#
Type is either flexible or userdefined.

int PyTypeNum_ISOBJECT(int num)#

int PyDataType_ISOBJECT(PyArray_Descr *descr)#

int PyArray_ISOBJECT(PyArrayObject *obj)#
Type represents object data type.

int PyTypeNum_ISBOOL(int num)#

int PyDataType_ISBOOL(PyArray_Descr *descr)#

int PyArray_ISBOOL(PyArrayObject *obj)#
Type represents Boolean data type.

int PyDataType_HASFIELDS(PyArray_Descr *descr)#

int PyArray_HASFIELDS(PyArrayObject *obj)#
Type has fields associated with it.

int PyArray_ISNOTSWAPPED(PyArrayObject *m)#
Evaluates true if the data area of the ndarray m is in machine byteorder according to the array’s datatype descriptor.

int PyArray_ISBYTESWAPPED(PyArrayObject *m)#
Evaluates true if the data area of the ndarray m is not in machine byteorder according to the array’s datatype descriptor.

npy_bool PyArray_EquivTypes(PyArray_Descr *type1, PyArray_Descr *type2)#
Return
NPY_TRUE
if type1 and type2 actually represent equivalent types for this platform (the fortran member of each type is ignored). For example, on 32bit platforms,NPY_LONG
andNPY_INT
are equivalent. Otherwise returnNPY_FALSE
.

npy_bool PyArray_EquivArrTypes(PyArrayObject *a1, PyArrayObject *a2)#
Return
NPY_TRUE
if a1 and a2 are arrays with equivalent types for this platform.

npy_bool PyArray_EquivTypenums(int typenum1, int typenum2)#
Special case of
PyArray_EquivTypes
(…) that does not accept flexible data types but may be easier to call.

int PyArray_EquivByteorders(int b1, int b2)#
True if byteorder characters b1 and b2 (
NPY_LITTLE
,NPY_BIG
,NPY_NATIVE
,NPY_IGNORE
) are either equal or equivalent as to their specification of a native byte order. Thus, on a littleendian machineNPY_LITTLE
andNPY_NATIVE
are equivalent where they are not equivalent on a bigendian machine.
Converting data types#

PyObject *PyArray_Cast(PyArrayObject *arr, int typenum)#
Mainly for backwards compatibility to the Numeric CAPI and for simple casts to nonflexible types. Return a new array object with the elements of arr cast to the datatype typenum which must be one of the enumerated types and not a flexible type.

PyObject *PyArray_CastToType(PyArrayObject *arr, PyArray_Descr *type, int fortran)#
Return a new array of the type specified, casting the elements of arr as appropriate. The fortran argument specifies the ordering of the output array.

int PyArray_CastTo(PyArrayObject *out, PyArrayObject *in)#
As of 1.6, this function simply calls
PyArray_CopyInto
, which handles the casting.Cast the elements of the array in into the array out. The output array should be writeable, have an integermultiple of the number of elements in the input array (more than one copy can be placed in out), and have a data type that is one of the builtin types. Returns 0 on success and 1 if an error occurs.

int PyArray_CanCastSafely(int fromtype, int totype)#
Returns nonzero if an array of data type fromtype can be cast to an array of data type totype without losing information. An exception is that 64bit integers are allowed to be cast to 64bit floating point values even though this can lose precision on large integers so as not to proliferate the use of long doubles without explicit requests. Flexible array types are not checked according to their lengths with this function.

int PyArray_CanCastTo(PyArray_Descr *fromtype, PyArray_Descr *totype)#
PyArray_CanCastTypeTo
supersedes this function in NumPy 1.6 and later.Equivalent to PyArray_CanCastTypeTo(fromtype, totype, NPY_SAFE_CASTING).

int PyArray_CanCastTypeTo(PyArray_Descr *fromtype, PyArray_Descr *totype, NPY_CASTING casting)#
New in version 1.6.
Returns nonzero if an array of data type fromtype (which can include flexible types) can be cast safely to an array of data type totype (which can include flexible types) according to the casting rule casting. For simple types with
NPY_SAFE_CASTING
, this is basically a wrapper aroundPyArray_CanCastSafely
, but for flexible types such as strings or unicode, it produces results taking into account their sizes. Integer and float types can only be cast to a string or unicode type usingNPY_SAFE_CASTING
if the string or unicode type is big enough to hold the max value of the integer/float type being cast from.

int PyArray_CanCastArrayTo(PyArrayObject *arr, PyArray_Descr *totype, NPY_CASTING casting)#
New in version 1.6.
Returns nonzero if arr can be cast to totype according to the casting rule given in casting. If arr is an array scalar, its value is taken into account, and nonzero is also returned when the value will not overflow or be truncated to an integer when converting to a smaller type.
This is almost the same as the result of PyArray_CanCastTypeTo(PyArray_MinScalarType(arr), totype, casting), but it also handles a special case arising because the set of uint values is not a subset of the int values for types with the same number of bits.

PyArray_Descr *PyArray_MinScalarType(PyArrayObject *arr)#
New in version 1.6.
If arr is an array, returns its data type descriptor, but if arr is an array scalar (has 0 dimensions), it finds the data type of smallest size to which the value may be converted without overflow or truncation to an integer.
This function will not demote complex to float or anything to boolean, but will demote a signed integer to an unsigned integer when the scalar value is positive.

PyArray_Descr *PyArray_PromoteTypes(PyArray_Descr *type1, PyArray_Descr *type2)#
New in version 1.6.
Finds the data type of smallest size and kind to which type1 and type2 may be safely converted. This function is symmetric and associative. A string or unicode result will be the proper size for storing the max value of the input types converted to a string or unicode.

PyArray_Descr *PyArray_ResultType(npy_intp narrs, PyArrayObject **arrs, npy_intp ndtypes, PyArray_Descr **dtypes)#
New in version 1.6.
This applies type promotion to all the input arrays and dtype objects, using the NumPy rules for combining scalars and arrays, to determine the output type for an operation with the given set of operands. This is the same result type that ufuncs produce.
See the documentation of
numpy.result_type
for more detail about the type promotion algorithm.

int PyArray_ObjectType(PyObject *op, int mintype)#
This function is superseded by
PyArray_MinScalarType
and/orPyArray_ResultType
.This function is useful for determining a common type that two or more arrays can be converted to. It only works for nonflexible array types as no itemsize information is passed. The mintype argument represents the minimum type acceptable, and op represents the object that will be converted to an array. The return value is the enumerated typenumber that represents the datatype that op should have.

PyArrayObject **PyArray_ConvertToCommonType(PyObject *op, int *n)#
The functionality this provides is largely superseded by iterator
NpyIter
introduced in 1.6, with flagNPY_ITER_COMMON_DTYPE
or with the same dtype parameter for all operands.Convert a sequence of Python objects contained in op to an array of ndarrays each having the same data type. The type is selected in the same way as
PyArray_ResultType
. The length of the sequence is returned in n, and an n length array ofPyArrayObject
pointers is the return value (orNULL
if an error occurs). The returned array must be freed by the caller of this routine (usingPyDataMem_FREE
) and all the array objects in itDECREF
‘d or a memoryleak will occur. The example templatecode below shows a typical usage:Changed in version 1.18.0: A mix of scalars and zerodimensional arrays now produces a type capable of holding the scalar value. Previously priority was given to the dtype of the arrays.
mps = PyArray_ConvertToCommonType(obj, &n); if (mps==NULL) return NULL; {code} <before return> for (i=0; i<n; i++) Py_DECREF(mps[i]); PyDataMem_FREE(mps); {return}

char *PyArray_Zero(PyArrayObject *arr)#
A pointer to newly created memory of size arr >itemsize that holds the representation of 0 for that type. The returned pointer, ret, must be freed using
PyDataMem_FREE
(ret) when it is not needed anymore.

char *PyArray_One(PyArrayObject *arr)#
A pointer to newly created memory of size arr >itemsize that holds the representation of 1 for that type. The returned pointer, ret, must be freed using
PyDataMem_FREE
(ret) when it is not needed anymore.
Userdefined data types#

void PyArray_InitArrFuncs(PyArray_ArrFuncs *f)#
Initialize all function pointers and members to
NULL
.

int PyArray_RegisterDataType(PyArray_DescrProto *dtype)#
Note
As of NumPy 2.0 this API is considered legacy, the new DType API is more powerful and provides additional flexibility. The API may eventually be deprecated but support is continued for the time being.
Compiling for NumPy 1.x and 2.x
NumPy 2.x requires passing in a
PyArray_DescrProto
typed struct rather than aPyArray_Descr
. This is necessary to allow changes. To allow code to run and compile on both 1.x and 2.x you need to change the type of your struct toPyArray_DescrProto
and add:/* Allow compiling on NumPy 1.x */ #if NPY_ABI_VERSION < 0x02000000 #define PyArray_DescrProto PyArray_Descr #endif
for 1.x compatibility. Further, the struct will not be the actual descriptor anymore, only it’s type number will be updated. After successful registration, you must thus fetch the actual dtype with:
int type_num = PyArray_RegisterDataType(&my_descr_proto); if (type_num < 0) { /* error */ } PyArray_Descr *my_descr = PyArray_DescrFromType(type_num);
With these two changes, the code should compile and work on both 1.x and 2.x or later.
Register a datatype as a new userdefined data type for arrays. The type must have most of its entries filled in. This is not always checked and errors can produce segfaults. In particular, the typeobj member of the
dtype
structure must be filled with a Python type that has a fixedsize elementsize that corresponds to the elsize member of dtype. Also thef
member must have the required functions: nonzero, copyswap, copyswapn, getitem, setitem, and cast (some of the cast functions may beNULL
if no support is desired). To avoid confusion, you should choose a unique character typecode but this is not enforced and not relied on internally.A userdefined type number is returned that uniquely identifies the type. A pointer to the new structure can then be obtained from
PyArray_DescrFromType
using the returned type number. A 1 is returned if an error occurs. If this dtype has already been registered (checked only by the address of the pointer), then return the previouslyassigned typenumber.

int PyArray_RegisterCastFunc(PyArray_Descr *descr, int totype, PyArray_VectorUnaryFunc *castfunc)#
Register a lowlevel casting function, castfunc, to convert from the datatype, descr, to the given datatype number, totype. Any old casting function is overwritten. A
0
is returned on success or a1
on failure.
type PyArray_VectorUnaryFunc#
The function pointer type for lowlevel casting functions.

type PyArray_VectorUnaryFunc#

int PyArray_RegisterCanCast(PyArray_Descr *descr, int totype, NPY_SCALARKIND scalar)#
Register the datatype number, totype, as castable from datatype object, descr, of the given scalar kind. Use scalar =
NPY_NOSCALAR
to register that an array of datatype descr can be cast safely to a datatype whose type_number is totype. The return value is 0 on success or 1 on failure.
Special functions for NPY_OBJECT#
Warning
When working with arrays or buffers filled with objects NumPy tries to
ensure such buffers are filled with None
before any data may be read.
However, code paths may existed where an array is only initialized to
NULL
.
NumPy itself accepts NULL
as an alias for None
, but may assert
nonNULL
when compiled in debug mode.
Because NumPy is not yet consistent about initialization with None,
users must expect a value of NULL
when working with buffers created
by NumPy. Users should also ensure to pass fully initialized buffers
to NumPy, since NumPy may make this a strong requirement in the future.
There is currently an intention to ensure that NumPy always initializes object arrays before they may be read. Any failure to do so will be regarded as a bug. In the future, users may be able to rely on nonNULL values when reading from any array, although exceptions for writing to freshly created arrays may remain (e.g. for output arrays in ufunc code). As of NumPy 1.23 known code paths exists where proper filling is not done.

int PyArray_INCREF(PyArrayObject *op)#
Used for an array, op, that contains any Python objects. It increments the reference count of every object in the array according to the datatype of op. A 1 is returned if an error occurs, otherwise 0 is returned.

void PyArray_Item_INCREF(char *ptr, PyArray_Descr *dtype)#
A function to INCREF all the objects at the location ptr according to the datatype dtype. If ptr is the start of a structured type with an object at any offset, then this will (recursively) increment the reference count of all objectlike items in the structured type.

int PyArray_XDECREF(PyArrayObject *op)#
Used for an array, op, that contains any Python objects. It decrements the reference count of every object in the array according to the datatype of op. Normal return value is 0. A 1 is returned if an error occurs.

void PyArray_Item_XDECREF(char *ptr, PyArray_Descr *dtype)#
A function to XDECREF all the objectlike items at the location ptr as recorded in the datatype, dtype. This works recursively so that if
dtype
itself has fields with datatypes that contain objectlike items, all the objectlike fields will be XDECREF'd
.

int PyArray_SetWritebackIfCopyBase(PyArrayObject *arr, PyArrayObject *base)#
Precondition:
arr
is a copy ofbase
(though possibly with different strides, ordering, etc.) Sets theNPY_ARRAY_WRITEBACKIFCOPY
flag andarr>base
, and setbase
to READONLY. CallPyArray_ResolveWritebackIfCopy
before callingPy_DECREF
in order to copy any changes back tobase
and reset the READONLY flag.Returns 0 for success, 1 for failure.
Array flags#
The flags
attribute of the PyArrayObject
structure contains
important information about the memory used by the array (pointed to
by the data member) This flag information must be kept accurate or
strange results and even segfaults may result.
There are 6 (binary) flags that describe the memory area used by the
data buffer. These constants are defined in arrayobject.h
and
determine the bitposition of the flag. Python exposes a nice
attribute based interface as well as a dictionarylike interface for
getting (and, if appropriate, setting) these flags.
Memory areas of all kinds can be pointed to by an ndarray, necessitating
these flags. If you get an arbitrary PyArrayObject
in Ccode, you
need to be aware of the flags that are set. If you need to guarantee
a certain kind of array (like NPY_ARRAY_C_CONTIGUOUS
and
NPY_ARRAY_BEHAVED
), then pass these requirements into the
PyArray_FromAny function.
In versions 1.6 and earlier of NumPy, the following flags did not have the _ARRAY_ macro namespace in them. That form of the constant names is deprecated in 1.7.
Basic Array Flags#
An ndarray can have a data segment that is not a simple contiguous chunk of wellbehaved memory you can manipulate. It may not be aligned with word boundaries (very important on some platforms). It might have its data in a different byteorder than the machine recognizes. It might not be writeable. It might be in Fortrancontiguous order. The array flags are used to indicate what can be said about data associated with an array.

NPY_ARRAY_C_CONTIGUOUS#
The data area is in Cstyle contiguous order (last index varies the fastest).

NPY_ARRAY_F_CONTIGUOUS#
The data area is in Fortranstyle contiguous order (first index varies the fastest).
Note
Arrays can be both Cstyle and Fortranstyle contiguous simultaneously. This is clear for 1dimensional arrays, but can also be true for higher dimensional arrays.
Even for contiguous arrays a stride for a given dimension
arr.strides[dim]
may be arbitrary if arr.shape[dim] == 1
or the array has no elements.
It does not generally hold that self.strides[1] == self.itemsize
for Cstyle contiguous arrays or self.strides[0] == self.itemsize
for
Fortranstyle contiguous arrays is true. The correct way to access the
itemsize
of an array from the C API is PyArray_ITEMSIZE(arr)
.
See also

NPY_ARRAY_OWNDATA#
The data area is owned by this array. Should never be set manually, instead create a
PyObject
wrapping the data and set the array’s base to that object. For an example, see the test intest_mem_policy
.

NPY_ARRAY_ALIGNED#
The data area and all array elements are aligned appropriately.

NPY_ARRAY_WRITEABLE#
The data area can be written to.
Notice that the above 3 flags are defined so that a new, well behaved array has these flags defined as true.

NPY_ARRAY_WRITEBACKIFCOPY#
The data area represents a (wellbehaved) copy whose information should be transferred back to the original when
PyArray_ResolveWritebackIfCopy
is called.This is a special flag that is set if this array represents a copy made because a user required certain flags in
PyArray_FromAny
and a copy had to be made of some other array (and the user asked for this flag to be set in such a situation). The base attribute then points to the “misbehaved” array (which is set read_only).PyArray_ResolveWritebackIfCopy
will copy its contents back to the “misbehaved” array (casting if necessary) and will reset the “misbehaved” array toNPY_ARRAY_WRITEABLE
. If the “misbehaved” array was notNPY_ARRAY_WRITEABLE
to begin with thenPyArray_FromAny
would have returned an error becauseNPY_ARRAY_WRITEBACKIFCOPY
would not have been possible.
PyArray_UpdateFlags
(obj, flags) will update the obj>flags
for flags
which can be any of NPY_ARRAY_C_CONTIGUOUS
,
NPY_ARRAY_F_CONTIGUOUS
, NPY_ARRAY_ALIGNED
, or
NPY_ARRAY_WRITEABLE
.
Combinations of array flags#

NPY_ARRAY_BEHAVED#

NPY_ARRAY_CARRAY#

NPY_ARRAY_CARRAY_RO#

NPY_ARRAY_FARRAY#

NPY_ARRAY_FARRAY_RO#

NPY_ARRAY_DEFAULT#

NPY_ARRAY_IN_ARRAY#

NPY_ARRAY_IN_FARRAY#

NPY_ARRAY_OUT_ARRAY#
NPY_ARRAY_C_CONTIGUOUS
NPY_ARRAY_WRITEABLE
NPY_ARRAY_ALIGNED

NPY_ARRAY_OUT_FARRAY#
NPY_ARRAY_F_CONTIGUOUS
NPY_ARRAY_WRITEABLE
NPY_ARRAY_ALIGNED

NPY_ARRAY_INOUT_ARRAY#
NPY_ARRAY_C_CONTIGUOUS
NPY_ARRAY_WRITEABLE
NPY_ARRAY_ALIGNED
NPY_ARRAY_WRITEBACKIFCOPY

NPY_ARRAY_INOUT_FARRAY#
NPY_ARRAY_F_CONTIGUOUS
NPY_ARRAY_WRITEABLE
NPY_ARRAY_ALIGNED
NPY_ARRAY_WRITEBACKIFCOPY

NPY_ARRAY_UPDATE_ALL#
NPY_ARRAY_C_CONTIGUOUS
NPY_ARRAY_F_CONTIGUOUS
NPY_ARRAY_ALIGNED
Flaglike constants#
These constants are used in PyArray_FromAny
(and its macro forms) to
specify desired properties of the new array.

NPY_ARRAY_FORCECAST#
Cast to the desired type, even if it can’t be done without losing information.

NPY_ARRAY_ENSURECOPY#
Make sure the resulting array is a copy of the original.

NPY_ARRAY_ENSUREARRAY#
Make sure the resulting object is an actual ndarray, and not a subclass.
These constants are used in PyArray_CheckFromAny
(and its macro forms)
to specify desired properties of the new array.

NPY_ARRAY_NOTSWAPPED#
Make sure the returned array has a datatype descriptor that is in machine byteorder, overriding any specification in the dtype argument. Normally, the byteorder requirement is determined by the dtype argument. If this flag is set and the dtype argument does not indicate a machine byteorder descriptor (or is NULL and the object is already an array with a datatype descriptor that is not in machine byte order), then a new datatype descriptor is created and used with its byteorder field set to native.

NPY_ARRAY_BEHAVED_NS#
NPY_ARRAY_ALIGNED
NPY_ARRAY_WRITEABLE
NPY_ARRAY_NOTSWAPPED

NPY_ARRAY_ELEMENTSTRIDES#
Make sure the returned array has strides that are multiples of the element size.
Flag checking#
For all of these macros arr must be an instance of a (subclass of)
PyArray_Type
.

int PyArray_CHKFLAGS(PyObject *arr, int flags)#
The first parameter, arr, must be an ndarray or subclass. The parameter, flags, should be an integer consisting of bitwise combinations of the possible flags an array can have:
NPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_F_CONTIGUOUS
,NPY_ARRAY_OWNDATA
,NPY_ARRAY_ALIGNED
,NPY_ARRAY_WRITEABLE
,NPY_ARRAY_WRITEBACKIFCOPY
.

int PyArray_ISFORTRAN(PyObject *arr)#
Evaluates true if arr is Fortranstyle contiguous and not Cstyle contiguous.
PyArray_IS_F_CONTIGUOUS
is the correct way to test for Fortranstyle contiguity.

int PyArray_ISALIGNED(PyObject *arr)#
Evaluates true if the data area of arr is properly aligned on the machine.

int PyArray_ISBEHAVED(PyObject *arr)#
Evaluates true if the data area of arr is aligned and writeable and in machine byteorder according to its descriptor.

int PyArray_ISBEHAVED_RO(PyObject *arr)#
Evaluates true if the data area of arr is aligned and in machine byteorder.

int PyArray_ISCARRAY(PyObject *arr)#
Evaluates true if the data area of arr is Cstyle contiguous, and
PyArray_ISBEHAVED
(arr) is true.

int PyArray_ISFARRAY(PyObject *arr)#
Evaluates true if the data area of arr is Fortranstyle contiguous and
PyArray_ISBEHAVED
(arr) is true.

int PyArray_ISCARRAY_RO(PyObject *arr)#
Evaluates true if the data area of arr is Cstyle contiguous, aligned, and in machine byteorder.

int PyArray_ISFARRAY_RO(PyObject *arr)#
Evaluates true if the data area of arr is Fortranstyle contiguous, aligned, and in machine byteorder .

int PyArray_ISONESEGMENT(PyObject *arr)#
Evaluates true if the data area of arr consists of a single (Cstyle or Fortranstyle) contiguous segment.

void PyArray_UpdateFlags(PyArrayObject *arr, int flagmask)#
The
NPY_ARRAY_C_CONTIGUOUS
,NPY_ARRAY_ALIGNED
, andNPY_ARRAY_F_CONTIGUOUS
array flags can be “calculated” from the array object itself. This routine updates one or more of these flags of arr as specified in flagmask by performing the required calculation.
Warning
It is important to keep the flags updated (using
PyArray_UpdateFlags
can help) whenever a manipulation with an
array is performed that might cause them to change. Later
calculations in NumPy that rely on the state of these flags do not
repeat the calculation to update them.

int PyArray_FailUnlessWriteable(PyArrayObject *obj, const char *name)#
This function does nothing and returns 0 if obj is writeable. It raises an exception and returns 1 if obj is not writeable. It may also do other housekeeping, such as issuing warnings on arrays which are transitioning to become views. Always call this function at some point before writing to an array.
name is a name for the array, used to give better error messages. It can be something like “assignment destination”, “output array”, or even just “array”.
ArrayMethod API#
ArrayMethod loops are intended as a generic mechanism for writing loops
over arrays, including ufunc loops and casts. The public API is defined in the
numpy/dtype_api.h
header. See PyArrayMethod_Context and PyArrayMethod_Spec for
documentation on the C structs exposed in the ArrayMethod API.
Slots and Typedefs#
These are used to identify which kind of function an ArrayMethod slot implements. See Slots and Typedefs below for documentation on the functions that must be implemented for each slot.

NPY_METH_resolve_descriptors#

typedef NPY_CASTING (PyArrayMethod_ResolveDescriptors)(struct PyArrayMethodObject_tag *method, PyArray_DTypeMeta **dtypes, PyArray_Descr **given_descrs, PyArray_Descr **loop_descrs, npy_intp *view_offset)#
The function used to set the descriptors for an operation based on the descriptors of the operands. For example, a ufunc operation with two input operands and one output operand that is called without
out
being set in the python API,resolve_descriptors
will be passed the descriptors for the two operands and determine the correct descriptor to use for the output based on the output DType set for the ArrayMethod. Ifout
is set, then the output descriptor would be passed in as well and should not be overridden.The method is a pointer to the underlying cast or ufunc loop. In the future we may expose this struct publicly but for now this is an opaque pointer and the method cannot be inspected. The dtypes is an
nargs
length array ofPyArray_DTypeMeta
pointers, given_descrs is annargs
length array of input descriptor instances (output descriptors may be NULL if no output was provided by the user), and loop_descrs is annargs
length array of descriptors that must be filled in by the resolve descriptors implementation. view_offset is currently only interesting for casts and can normally be ignored. When a cast does not require any operation, this can be signalled by settingview_offset
to 0. On error, you must return(NPY_CASTING)1
with an error set.

NPY_METH_strided_loop#

NPY_METH_contiguous_loop#

NPY_METH_unaligned_strided_loop#

NPY_METH_unaligned_contiguous_loop#
One dimensional strided loops implementing the behavior (either a ufunc or cast). In most cases,
NPY_METH_strided_loop
is the generic and only version that needs to be implemented.NPY_METH_contiguous_loop
can be implemented additionally as a more lightweight/faster version and it is used when all inputs and outputs are contiguous.To deal with possibly unaligned data, NumPy needs to be able to copy unaligned to aligned data. When implementing a new DType, the “cast” or copy for it needs to implement
NPY_METH_unaligned_strided_loop
. Unlike the normal versions, this loop must not assume that the data can be accessed in an aligned fashion. These loops must copy each value before accessing or storing:type_in in_value; type_out out_value memcpy(&value, in_data, sizeof(type_in)); out_value = in_value; memcpy(out_data, &out_value, sizeof(type_out)
while a normal loop can just use:
*(type_out *)out_data = *(type_in)in_data;
The unaligned loops are currently only used in casts and will never be picked in ufuncs (ufuncs create a temporary copy to ensure aligned inputs). These slot IDs are ignored when
NPY_METH_get_loop
is defined, where instead whichever loop returned by theget_loop
function is used.

NPY_METH_contiguous_indexed_loop#
A specialized innerloop option to speed up common
ufunc.at
computations.

typedef int (PyArrayMethod_StridedLoop)(PyArrayMethod_Context *context, char *const *data, const npy_intp *dimensions, const npy_intp *strides, NpyAuxData *auxdata)#
An implementation of an ArrayMethod loop. All of the loop slot IDs listed above must provide a
PyArrayMethod_StridedLoop
implementation. The context is a struct containing context for the loop operation  in particular the input descriptors. The data are an array of pointers to the beginning of the input and output array buffers. The dimensions are the loop dimensions for the operation. The strides are annargs
length array of strides for each input. The auxdata is an optional set of auxiliary data that can be passed in to the loop  helpful to turn on and off optional behavior or reduce boilerplate by allowing similar ufuncs to share loop implementations or to allocate space that is persistent over multiple strided loop calls.

NPY_METH_get_loop#
Allows more finegrained control over loop selection. Accepts an implementation of PyArrayMethod_GetLoop, which in turn returns a strided loop implementation. If
NPY_METH_get_loop
is defined, the other loop slot IDs are ignored, if specified.

typedef int (PyArrayMethod_GetLoop)(PyArrayMethod_Context *context, int aligned, int move_references, const npy_intp *strides, PyArrayMethod_StridedLoop **out_loop, NpyAuxData **out_transferdata, NPY_ARRAYMETHOD_FLAGS *flags);#
Sets the loop to use for an operation at runtime. The context is the runtime context for the operation. aligned indicates whether the data access for the loop is aligned (1) or unaligned (0). move_references indicates whether embedded references in the data should be copied. strides are the strides for the input array, out_loop is a pointer that must be filled in with a pointer to the loop implementation. out_transferdata can be optionally filled in to allow passing in extra userdefined context to an operation. flags must be filled in with ArrayMethod flags relevant for the operation. This is for example necessary to indicate if the inner loop requires the Python GIL to be held.

NPY_METH_get_reduction_initial#

typedef int (PyArrayMethod_GetReductionInitial)(PyArrayMethod_Context *context, npy_bool reduction_is_empty, char *initial)#
Query an ArrayMethod for the initial value for use in reduction. The context is the ArrayMethod context, mainly to access the input descriptors. reduction_is_empty indicates whether the reduction is empty. When it is, the value returned may differ. In this case it is a “default” value that may differ from the “identity” value normally used. For example:
0.0
is the default forsum([])
. But0.0
is the correct identity otherwise as it preserves the sign forsum([0.0])
.We use no identity for object, but return the default of
0
and1
for the emptysum([], dtype=object)
andprod([], dtype=object)
. This allowsnp.sum(np.array(["a", "b"], dtype=object))
to work.inf
orINT_MIN
formax
is an identity, but at leastINT_MIN
not a good default when there are no items.
initial is a pointer to the data for the initial value, which should be filled in. Returns 1, 0, or 1 indicating error, no initial value, and the initial value being successfully filled. Errors must not be given when no initial value is correct, since NumPy may call this even when it is not strictly necessary to do so.
Flags#

enum NPY_ARRAYMETHOD_FLAGS#
These flags allow switching on and off custom runtime behavior for ArrayMethod loops. For example, if a ufunc cannot possibly trigger floating point errors, then the
NPY_METH_NO_FLOATINGPOINT_ERRORS
flag should be set on the ufunc when it is registered.
enumerator NPY_METH_REQUIRES_PYAPI#
Indicates the method must hold the GIL. If this flag is not set, the GIL is released before the loop is called.

enumerator NPY_METH_NO_FLOATINGPOINT_ERRORS#
Indicates the method cannot generate floating errors, so checking for floating errors after the loop completes can be skipped.

enumerator NPY_METH_SUPPORTS_UNALIGNED#
Indicates the method supports unaligned access.

enumerator NPY_METH_IS_REORDERABLE#
Indicates that the result of applying the loop repeatedly (for example, in a reduction operation) does not depend on the order of application.

enumerator NPY_METH_RUNTIME_FLAGS#
The flags that can be changed at runtime.

enumerator NPY_METH_REQUIRES_PYAPI#
Typedefs#
Typedefs for functions that users of the ArrayMethod API can implement are described below.

typedef int (PyArrayMethod_TraverseLoop)(void *traverse_context, PyArray_Descr *descr, char *data, npy_intp size, npy_intp stride, NpyAuxData *auxdata)#
A traverse loop working on a single array. This is similar to the general stridedloop function. This is designed for loops that need to visit every element of a single array.
Currently this is used for array clearing, via the
NPY_DT_get_clear_loop
DType API hook, and zerofilling, via theNPY_DT_get_fill_zero_loop
DType API hook. These are most useful for handling arrays storing embedded references to python objects or heapallocated data.The descr is the descriptor for the array, data is a pointer to the array buffer, size is the 1D size of the array buffer, stride is the stride, and auxdata is optional extra data for the loop.
The traverse_context is passed in because we may need to pass in Interpreter state or similar in the future, but we don’t want to pass in a full context (with pointers to dtypes, method, caller which all make no sense for a traverse function). We assume for now that this context can be just passed through in the future (for structured dtypes).

typedef int (PyArrayMethod_GetTraverseLoop)(void *traverse_context, PyArray_Descr *descr, int aligned, npy_intp fixed_stride, PyArrayMethod_TraverseLoop **out_loop, NpyAuxData **out_auxdata, NPY_ARRAYMETHOD_FLAGS *flags)#
Simplified get_loop function specific to dtype traversal
It should set the flags needed for the traversal loop and set out_loop to the loop function, which must be a valid
PyArrayMethod_TraverseLoop
pointer. Currently this is used for zerofilling and clearing arrays storing embedded references.
API Functions and Typedefs#
These functions are part of the main numpy array API and were added along with the rest of the ArrayMethod API.

int PyUFunc_AddLoopFromSpec(PyObject *ufunc, PyArrayMethod_Spec *spec)#
Add loop directly to a ufunc from a given ArrayMethod spec. the main ufunc registration function. This adds a new implementation/loop to a ufunc. It replaces PyUFunc_RegisterLoopForType.

int PyUFunc_AddPromoter(PyObject *ufunc, PyObject *DType_tuple, PyObject *promoter)#
Note that currently the output dtypes are always
NULL
unless they are also part of the signature. This is an implementation detail and could change in the future. However, in general promoters should not have a need for output dtypes. Register a new promoter for a ufunc. The first argument is the ufunc to register the promoter with. The second argument is a Python tuple containing DTypes or None matching the number of inputs and outputs for the ufuncs. The last argument is a promoter is a function stored in a PyCapsule. It is passed the operation and requested DType signatures and can mutate it to attempt a new search for a matching loop/promoter.

typedef int (PyArrayMethod_PromoterFunction)(PyObject *ufunc, PyArray_DTypeMeta *op_dtypes[], PyArray_DTypeMeta *signature[], PyArray_DTypeMeta *new_op_dtypes[])#
Type of the promoter function, which must be wrapped into a
PyCapsule
with name"numpy._ufunc_promoter"
. It is passed the operation and requested DType signatures and can mutate the signatures to attempt a search for a new loop or promoter that can accomplish the operation by casting the inputs to the “promoted” DTypes.

int PyUFunc_GiveFloatingpointErrors(const char *name, int fpe_errors)#
Checks for a floating point error after performing a floating point operation in a manner that takes into account the error signaling configured via
numpy.errstate
. Takes the name of the operation to use in the error message and an integer flag that is one ofNPY_FPE_DIVIDEBYZERO
,NPY_FPE_OVERFLOW
,NPY_FPE_UNDERFLOW
,NPY_FPE_INVALID
to indicate which error to check for.Returns 1 on failure (an error was raised) and 0 on success.

int PyUFunc_AddWrappingLoop(PyObject *ufunc_obj, PyArray_DTypeMeta *new_dtypes[], PyArray_DTypeMeta *wrapped_dtypes[], PyArrayMethod_TranslateGivenDescriptors *translate_given_descrs, PyArrayMethod_TranslateLoopDescriptors *translate_loop_descrs)#
Allows creating of a fairly lightweight wrapper around an existing ufunc loop. The idea is mainly for units, as this is currently slightly limited in that it enforces that you cannot use a loop from another ufunc.

typedef int (PyArrayMethod_TranslateGivenDescriptors)(int nin, int nout, PyArray_DTypeMeta *wrapped_dtypes[], PyArray_Descr *given_descrs[], PyArray_Descr *new_descrs[]);#
The function to convert the given descriptors (passed in to
resolve_descriptors
) and translates them for the wrapped loop. The new descriptors MUST be viewable with the old ones, NULL must be supported (for output arguments) and should normally be forwarded.The output of of this function will be used to construct views of the arguments as if they were the translated dtypes and does not use a cast. This means this mechanism is mostly useful for DTypes that “wrap” another DType implementation. For example, a unit DType could use this to wrap an existing floating point DType without needing to reimplement lowlevel ufunc logic. In the unit example,
resolve_descriptors
would handle computing the output unit from the input unit.

typedef int (PyArrayMethod_TranslateLoopDescriptors)(int nin, int nout, PyArray_DTypeMeta *new_dtypes[], PyArray_Descr *given_descrs[], PyArray_Descr *original_descrs[], PyArray_Descr *loop_descrs[]);#
The function to convert the actual loop descriptors (as returned by the original resolve_descriptors function) to the ones the output array should use. This function must return “viewable” types, it must not mutate them in any form that would break the innerloop logic. Does not need to support NULL.
Wrapping Loop Example#
Suppose you want to wrap the float64
multiply implementation for a
WrappedDoubleDType
. You would add a wrapping loop like so:
PyArray_DTypeMeta *orig_dtypes[3] = {
&WrappedDoubleDType, &WrappedDoubleDType, &WrappedDoubleDType};
PyArray_DTypeMeta *wrapped_dtypes[3] = {
&PyArray_Float64DType, &PyArray_Float64DType, &PyArray_Float64DType}
PyObject *mod = PyImport_ImportModule("numpy");
if (mod == NULL) {
return 1;
}
PyObject *multiply = PyObject_GetAttrString(mod, "multiply");
Py_DECREF(mod);
if (multiply == NULL) {
return 1;
}
int res = PyUFunc_AddWrappingLoop(
multiply, orig_dtypes, wrapped_dtypes, &translate_given_descrs
&translate_loop_descrs);
Py_DECREF(multiply);
Note that this also requires two functions to be defined above this code:
static int
translate_given_descrs(int nin, int nout,
PyArray_DTypeMeta *NPY_UNUSED(wrapped_dtypes[]),
PyArray_Descr *given_descrs[],
PyArray_Descr *new_descrs[])
{
for (int i = 0; i < nin + nout; i++) {
if (given_descrs[i] == NULL) {
new_descrs[i] = NULL;
}
else {
new_descrs[i] = PyArray_DescrFromType(NPY_DOUBLE);
}
}
return 0;
}
static int
translate_loop_descrs(int nin, int NPY_UNUSED(nout),
PyArray_DTypeMeta *NPY_UNUSED(new_dtypes[]),
PyArray_Descr *given_descrs[],
PyArray_Descr *original_descrs[],
PyArray_Descr *loop_descrs[])
{
// more complicated parametric DTypes may need to
// to do additional checking, but we know the wrapped
// DTypes *have* to be float64 for this example.
loop_descrs[0] = PyArray_DescrFromType(NPY_FLOAT64);
Py_INCREF(loop_descrs[0]);
loop_descrs[1] = PyArray_DescrFromType(NPY_FLOAT64);
Py_INCREF(loop_descrs[1]);
loop_descrs[2] = PyArray_DescrFromType(NPY_FLOAT64);
Py_INCREF(loop_descrs[2]);
}
API for calling array methods#
Conversion#

PyObject *PyArray_GetField(PyArrayObject *self, PyArray_Descr *dtype, int offset)#
Equivalent to
ndarray.getfield
(self, dtype, offset). This function steals a reference toPyArray_Descr
and returns a new array of the given dtype using the data in the current array at a specified offset in bytes. The offset plus the itemsize of the new array type must be less thanself>descr>elsize
or an error is raised. The same shape and strides as the original array are used. Therefore, this function has the effect of returning a field from a structured array. But, it can also be used to select specific bytes or groups of bytes from any array type.

int PyArray_SetField(PyArrayObject *self, PyArray_Descr *dtype, int offset, PyObject *val)#
Equivalent to
ndarray.setfield
(self, val, dtype, offset ). Set the field starting at offset in bytes and of the given dtype to val. The offset plus dtype >elsize must be less than self >descr>elsize or an error is raised. Otherwise, the val argument is converted to an array and copied into the field pointed to. If necessary, the elements of val are repeated to fill the destination array, But, the number of elements in the destination must be an integer multiple of the number of elements in val.

PyObject *PyArray_Byteswap(PyArrayObject *self, npy_bool inplace)#
Equivalent to
ndarray.byteswap
(self, inplace). Return an array whose data area is byteswapped. If inplace is nonzero, then do the byteswap inplace and return a reference to self. Otherwise, create a byteswapped copy and leave self unchanged.

PyObject *PyArray_NewCopy(PyArrayObject *old, NPY_ORDER order)#
Equivalent to
ndarray.copy
(self, fortran). Make a copy of the old array. The returned array is always aligned and writeable with data interpreted the same as the old array. If order isNPY_CORDER
, then a Cstyle contiguous array is returned. If order isNPY_FORTRANORDER
, then a Fortranstyle contiguous array is returned. If order isNPY_ANYORDER
, then the array returned is Fortranstyle contiguous only if the old one is; otherwise, it is Cstyle contiguous.

PyObject *PyArray_ToList(PyArrayObject *self)#
Equivalent to
ndarray.tolist
(self). Return a nested Python list from self.

PyObject *PyArray_ToString(PyArrayObject *self, NPY_ORDER order)#
Equivalent to
ndarray.tobytes
(self, order). Return the bytes of this array in a Python string.

PyObject *PyArray_ToFile(PyArrayObject *self, FILE *fp, char *sep, char *format)#
Write the contents of self to the file pointer fp in Cstyle contiguous fashion. Write the data as binary bytes if sep is the string “”or
NULL
. Otherwise, write the contents of self as text using the sep string as the item separator. Each item will be printed to the file. If the format string is notNULL
or “”, then it is a Python print statement format string showing how the items are to be written.

int PyArray_Dump(PyObject *self, PyObject *file, int protocol)#
Pickle the object in self to the given file (either a string or a Python file object). If file is a Python string it is considered to be the name of a file which is then opened in binary mode. The given protocol is used (if protocol is negative, or the highest available is used). This is a simple wrapper around cPickle.dump(self, file, protocol).

PyObject *PyArray_Dumps(PyObject *self, int protocol)#
Pickle the object in self to a Python string and return it. Use the Pickle protocol provided (or the highest available if protocol is negative).

int PyArray_FillWithScalar(PyArrayObject *arr, PyObject *obj)#
Fill the array, arr, with the given scalar object, obj. The object is first converted to the data type of arr, and then copied into every location. A 1 is returned if an error occurs, otherwise 0 is returned.

PyObject *PyArray_View(PyArrayObject *self, PyArray_Descr *dtype, PyTypeObject *ptype)#
Equivalent to
ndarray.view
(self, dtype). Return a new view of the array self as possibly a different datatype, dtype, and different array subclass ptype.If dtype is
NULL
, then the returned array will have the same data type as self. The new datatype must be consistent with the size of self. Either the itemsizes must be identical, or self must be singlesegment and the total number of bytes must be the same. In the latter case the dimensions of the returned array will be altered in the last (or first for Fortranstyle contiguous arrays) dimension. The data area of the returned array and self is exactly the same.
Shape Manipulation#

PyObject *PyArray_Newshape(PyArrayObject *self, PyArray_Dims *newshape, NPY_ORDER order)#
Result will be a new array (pointing to the same memory location as self if possible), but having a shape given by newshape. If the new shape is not compatible with the strides of self, then a copy of the array with the new specified shape will be returned.

PyObject *PyArray_Reshape(PyArrayObject *self, PyObject *shape)#
Equivalent to
ndarray.reshape
(self, shape) where shape is a sequence. Converts shape to aPyArray_Dims
structure and callsPyArray_Newshape
internally. For backward compatibility – Not recommended

PyObject *PyArray_Squeeze(PyArrayObject *self)#
Equivalent to
ndarray.squeeze
(self). Return a new view of self with all of the dimensions of length 1 removed from the shape.
Warning
matrix objects are always 2dimensional. Therefore,
PyArray_Squeeze
has no effect on arrays of matrix subclass.

PyObject *PyArray_SwapAxes(PyArrayObject *self, int a1, int a2)#
Equivalent to
ndarray.swapaxes
(self, a1, a2). The returned array is a new view of the data in self with the given axes, a1 and a2, swapped.

PyObject *PyArray_Resize(PyArrayObject *self, PyArray_Dims *newshape, int refcheck, NPY_ORDER fortran)#
Equivalent to
ndarray.resize
(self, newshape, refcheck=
refcheck, order= fortran ). This function only works on singlesegment arrays. It changes the shape of self inplace and will reallocate the memory for self if newshape has a different total number of elements then the old shape. If reallocation is necessary, then self must own its data, have self >base==NULL
, have self >weakrefs==NULL
, and (unless refcheck is 0) not be referenced by any other array. The fortran argument can beNPY_ANYORDER
,NPY_CORDER
, orNPY_FORTRANORDER
. It currently has no effect. Eventually it could be used to determine how the resize operation should view the data when constructing a differentlydimensioned array. Returns None on success and NULL on error.

PyObject *PyArray_Transpose(PyArrayObject *self, PyArray_Dims *permute)#
Equivalent to
ndarray.transpose
(self, permute). Permute the axes of the ndarray object self according to the data structure permute and return the result. If permute isNULL
, then the resulting array has its axes reversed. For example if self has shape \(10\times20\times30\), and permute.ptr
is (0,2,1) the shape of the result is \(10\times30\times20.\) If permute isNULL
, the shape of the result is \(30\times20\times10.\)

PyObject *PyArray_Flatten(PyArrayObject *self, NPY_ORDER order)#
Equivalent to
ndarray.flatten
(self, order). Return a 1d copy of the array. If order isNPY_FORTRANORDER
the elements are scanned out in Fortran order (firstdimension varies the fastest). If order isNPY_CORDER
, the elements ofself
are scanned in Corder (last dimension varies the fastest). If orderNPY_ANYORDER
, then the result ofPyArray_ISFORTRAN
(self) is used to determine which order to flatten.

PyObject *PyArray_Ravel(PyArrayObject *self, NPY_ORDER order)#
Equivalent to self.ravel(order). Same basic functionality as
PyArray_Flatten
(self, order) except if order is 0 and self is Cstyle contiguous, the shape is altered but no copy is performed.
Item selection and manipulation#

PyObject *PyArray_TakeFrom(PyArrayObject *self, PyObject *indices, int axis, PyArrayObject *ret, NPY_CLIPMODE clipmode)#
Equivalent to
ndarray.take
(self, indices, axis, ret, clipmode) except axis =None in Python is obtained by setting axis =NPY_MAXDIMS
in C. Extract the items from self indicated by the integervalued indices along the given axis. The clipmode argument can beNPY_RAISE
,NPY_WRAP
, orNPY_CLIP
to indicate what to do with outofbound indices. The ret argument can specify an output array rather than having one created internally.

PyObject *PyArray_PutTo(PyArrayObject *self, PyObject *values, PyObject *indices, NPY_CLIPMODE clipmode)#
Equivalent to self.put(values, indices, clipmode ). Put values into self at the corresponding (flattened) indices. If values is too small it will be repeated as necessary.

PyObject *PyArray_PutMask(PyArrayObject *self, PyObject *values, PyObject *mask)#
Place the values in self wherever corresponding positions (using a flattened context) in mask are true. The mask and self arrays must have the same total number of elements. If values is too small, it will be repeated as necessary.

PyObject *PyArray_Repeat(PyArrayObject *self, PyObject *op, int axis)#
Equivalent to
ndarray.repeat
(self, op, axis). Copy the elements of self, op times along the given axis. Either op is a scalar integer or a sequence of length self >dimensions[ axis ] indicating how many times to repeat each item along the axis.

PyObject *PyArray_Choose(PyArrayObject *self, PyObject *op, PyArrayObject *ret, NPY_CLIPMODE clipmode)#
Equivalent to
ndarray.choose
(self, op, ret, clipmode). Create a new array by selecting elements from the sequence of arrays in op based on the integer values in self. The arrays must all be broadcastable to the same shape and the entries in self should be between 0 and len(op). The output is placed in ret unless it isNULL
in which case a new output is created. The clipmode argument determines behavior for when entries in self are not between 0 and len(op).
NPY_RAISE#
raise a ValueError;

NPY_WRAP#
wrap values < 0 by adding len(op) and values >=len(op) by subtracting len(op) until they are in range;

NPY_CLIP#
all values are clipped to the region [0, len(op) ).

NPY_RAISE#

PyObject *PyArray_Sort(PyArrayObject *self, int axis, NPY_SORTKIND kind)#
Equivalent to
ndarray.sort
(self, axis, kind). Return an array with the items of self sorted along axis. The array is sorted using the algorithm denoted by kind, which is an integer/enum pointing to the type of sorting algorithms used.

PyObject *PyArray_ArgSort(PyArrayObject *self, int axis)#
Equivalent to
ndarray.argsort
(self, axis). Return an array of indices such that selection of these indices along the givenaxis
would return a sorted version of self. If self >descr is a datatype with fields defined, then self>descr>names is used to determine the sort order. A comparison where the first field is equal will use the second field and so on. To alter the sort order of a structured array, create a new datatype with a different order of names and construct a view of the array with that new datatype.

PyObject *PyArray_LexSort(PyObject *sort_keys, int axis)#
Given a sequence of arrays (sort_keys) of the same shape, return an array of indices (similar to
PyArray_ArgSort
(…)) that would sort the arrays lexicographically. A lexicographic sort specifies that when two keys are found to be equal, the order is based on comparison of subsequent keys. A merge sort (which leaves equal entries unmoved) is required to be defined for the types. The sort is accomplished by sorting the indices first using the first sort_key and then using the second sort_key and so forth. This is equivalent to the lexsort(sort_keys, axis) Python command. Because of the way the mergesort works, be sure to understand the order the sort_keys must be in (reversed from the order you would use when comparing two elements).If these arrays are all collected in a structured array, then
PyArray_Sort
(…) can also be used to sort the array directly.

PyObject *PyArray_SearchSorted(PyArrayObject *self, PyObject *values, NPY_SEARCHSIDE side, PyObject *perm)#
Equivalent to
ndarray.searchsorted
(self, values, side, perm). Assuming self is a 1d array in ascending order, then the output is an array of indices the same shape as values such that, if the elements in values were inserted before the indices, the order of self would be preserved. No checking is done on whether or not self is in ascending order.The side argument indicates whether the index returned should be that of the first suitable location (if
NPY_SEARCHLEFT
) or of the last (ifNPY_SEARCHRIGHT
).The sorter argument, if not
NULL
, must be a 1D array of integer indices the same length as self, that sorts it into ascending order. This is typically the result of a call toPyArray_ArgSort
(…) Binary search is used to find the required insertion points.

int PyArray_Partition(PyArrayObject *self, PyArrayObject *ktharray, int axis, NPY_SELECTKIND which)#
Equivalent to
ndarray.partition
(self, ktharray, axis, kind). Partitions the array so that the values of the element indexed by ktharray are in the positions they would be if the array is fully sorted and places all elements smaller than the kth before and all elements equal or greater after the kth element. The ordering of all elements within the partitions is undefined. If self>descr is a datatype with fields defined, then self>descr>names is used to determine the sort order. A comparison where the first field is equal will use the second field and so on. To alter the sort order of a structured array, create a new datatype with a different order of names and construct a view of the array with that new datatype. Returns zero on success and 1 on failure.

PyObject *PyArray_ArgPartition(PyArrayObject *op, PyArrayObject *ktharray, int axis, NPY_SELECTKIND which)#
Equivalent to
ndarray.argpartition
(self, ktharray, axis, kind). Return an array of indices such that selection of these indices along the givenaxis
would return a partitioned version of self.

PyObject *PyArray_Diagonal(PyArrayObject *self, int offset, int axis1, int axis2)#
Equivalent to
ndarray.diagonal
(self, offset, axis1, axis2 ). Return the offset diagonals of the 2d arrays defined by axis1 and axis2.

npy_intp PyArray_CountNonzero(PyArrayObject *self)#
New in version 1.6.
Counts the number of nonzero elements in the array object self.

PyObject *PyArray_Nonzero(PyArrayObject *self)#
Equivalent to
ndarray.nonzero
(self). Returns a tuple of index arrays that select elements of self that are nonzero. If (nd=PyArray_NDIM
(self
))==1, then a single index array is returned. The index arrays have data typeNPY_INTP
. If a tuple is returned (nd \(\neq\) 1), then its length is nd.

PyObject *PyArray_Compress(PyArrayObject *self, PyObject *condition, int axis, PyArrayObject *out)#
Equivalent to
ndarray.compress
(self, condition, axis ). Return the elements along axis corresponding to elements of condition that are true.
Calculation#
Tip
Pass in NPY_RAVEL_AXIS
for axis in order to achieve the same
effect that is obtained by passing in axis=None
in Python
(treating the array as a 1d array).
Note
The out argument specifies where to place the result. If out is
NULL, then the output array is created, otherwise the output is
placed in out which must be the correct size and type. A new
reference to the output array is always returned even when out
is not NULL. The caller of the routine has the responsibility
to Py_DECREF
out if not NULL or a memoryleak will occur.

PyObject *PyArray_ArgMax(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.argmax
(self, axis). Return the index of the largest element of self along axis.

PyObject *PyArray_ArgMin(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.argmin
(self, axis). Return the index of the smallest element of self along axis.

PyObject *PyArray_Max(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.max
(self, axis). Returns the largest element of self along the given axis. When the result is a single element, returns a numpy scalar instead of an ndarray.

PyObject *PyArray_Min(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.min
(self, axis). Return the smallest element of self along the given axis. When the result is a single element, returns a numpy scalar instead of an ndarray.

PyObject *PyArray_Ptp(PyArrayObject *self, int axis, PyArrayObject *out)#
Return the difference between the largest element of self along axis and the smallest element of self along axis. When the result is a single element, returns a numpy scalar instead of an ndarray.
Note
The rtype argument specifies the datatype the reduction should
take place over. This is important if the datatype of the array
is not “large” enough to handle the output. By default, all
integer datatypes are made at least as large as NPY_LONG
for the “add” and “multiply” ufuncs (which form the basis for
mean, sum, cumsum, prod, and cumprod functions).

PyObject *PyArray_Mean(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.mean
(self, axis, rtype). Returns the mean of the elements along the given axis, using the enumerated type rtype as the data type to sum in. Default sum behavior is obtained usingNPY_NOTYPE
for rtype.

PyObject *PyArray_Trace(PyArrayObject *self, int offset, int axis1, int axis2, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.trace
(self, offset, axis1, axis2, rtype). Return the sum (using rtype as the data type of summation) over the offset diagonal elements of the 2d arrays defined by axis1 and axis2 variables. A positive offset chooses diagonals above the main diagonal. A negative offset selects diagonals below the main diagonal.

PyObject *PyArray_Clip(PyArrayObject *self, PyObject *min, PyObject *max)#
Equivalent to
ndarray.clip
(self, min, max). Clip an array, self, so that values larger than max are fixed to max and values less than min are fixed to min.

PyObject *PyArray_Conjugate(PyArrayObject *self, PyArrayObject *out)#
Equivalent to
ndarray.conjugate
(self). Return the complex conjugate of self. If self is not of complex data type, then return self with a reference. Parameters:
self – Input array.
out – Output array. If provided, the result is placed into this array.
 Returns:
The complex conjugate of self.

PyObject *PyArray_Round(PyArrayObject *self, int decimals, PyArrayObject *out)#
Equivalent to
ndarray.round
(self, decimals, out). Returns the array with elements rounded to the nearest decimal place. The decimal place is defined as the \(10^{\textrm{decimals}}\) digit so that negative decimals cause rounding to the nearest 10’s, 100’s, etc. If out isNULL
, then the output array is created, otherwise the output is placed in out which must be the correct size and type.

PyObject *PyArray_Std(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.std
(self, axis, rtype). Return the standard deviation using data along axis converted to data type rtype.

PyObject *PyArray_Sum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.sum
(self, axis, rtype). Return 1d vector sums of elements in self along axis. Perform the sum after converting data to data type rtype.

PyObject *PyArray_CumSum(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.cumsum
(self, axis, rtype). Return cumulative 1d sums of elements in self along axis. Perform the sum after converting data to data type rtype.

PyObject *PyArray_Prod(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.prod
(self, axis, rtype). Return 1d products of elements in self along axis. Perform the product after converting data to data type rtype.

PyObject *PyArray_CumProd(PyArrayObject *self, int axis, int rtype, PyArrayObject *out)#
Equivalent to
ndarray.cumprod
(self, axis, rtype). Return 1d cumulative products of elements inself
alongaxis
. Perform the product after converting data to data typertype
.

PyObject *PyArray_All(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.all
(self, axis). Return an array with True elements for every 1d subarray ofself
defined byaxis
in which all the elements are True.

PyObject *PyArray_Any(PyArrayObject *self, int axis, PyArrayObject *out)#
Equivalent to
ndarray.any
(self, axis). Return an array with True elements for every 1d subarray of self defined by axis in which any of the elements are True.
Functions#
Array Functions#

int PyArray_AsCArray(PyObject **op, void *ptr, npy_intp *dims, int nd, PyArray_Descr *typedescr)#
Sometimes it is useful to access a multidimensional array as a Cstyle multidimensional array so that algorithms can be implemented using C’s a[i][j][k] syntax. This routine returns a pointer, ptr, that simulates this kind of Cstyle array, for 1, 2, and 3d ndarrays.
 Parameters:
op – The address to any Python object. This Python object will be replaced with an equivalent wellbehaved, Cstyle contiguous, ndarray of the given data type specified by the last two arguments. Be sure that stealing a reference in this way to the input object is justified.
ptr – The address to a (ctype* for 1d, ctype** for 2d or ctype*** for 3d) variable where ctype is the equivalent Ctype for the data type. On return, ptr will be addressable as a 1d, 2d, or 3d array.
dims – An output array that contains the shape of the array object. This array gives boundaries on any looping that will take place.
nd – The dimensionality of the array (1, 2, or 3).
typedescr – A
PyArray_Descr
structure indicating the desired datatype (including required byteorder). The call will steal a reference to the parameter.
Note
The simulation of a Cstyle array is not complete for 2d and 3d arrays. For example, the simulated arrays of pointers cannot be passed to subroutines expecting specific, staticallydefined 2d and 3d arrays. To pass to functions requiring those kind of inputs, you must statically define the required array and copy data.

int PyArray_Free(PyObject *op, void *ptr)#
Must be called with the same objects and memory locations returned from
PyArray_AsCArray
(…). This function cleans up memory that otherwise would get leaked.

PyObject *PyArray_Concatenate(PyObject *obj, int axis)#
Join the sequence of objects in obj together along axis into a single array. If the dimensions or types are not compatible an error is raised.

PyObject *PyArray_InnerProduct(PyObject *obj1, PyObject *obj2)#
Compute a productsum over the last dimensions of obj1 and obj2. Neither array is conjugated.

PyObject *PyArray_MatrixProduct(PyObject *obj1, PyObject *obj)#
Compute a productsum over the last dimension of obj1 and the secondtolast dimension of obj2. For 2d arrays this is a matrixproduct. Neither array is conjugated.

PyObject *PyArray_MatrixProduct2(PyObject *obj1, PyObject *obj, PyArrayObject *out)#
New in version 1.6.
Same as PyArray_MatrixProduct, but store the result in out. The output array must have the correct shape, type, and be Ccontiguous, or an exception is raised.

PyArrayObject *PyArray_EinsteinSum(char *subscripts, npy_intp nop, PyArrayObject **op_in, PyArray_Descr *dtype, NPY_ORDER order, NPY_CASTING casting, PyArrayObject *out)#
New in version 1.6.
Applies the Einstein summation convention to the array operands provided, returning a new array or placing the result in out. The string in subscripts is a comma separated list of index letters. The number of operands is in nop, and op_in is an array containing those operands. The data type of the output can be forced with dtype, the output order can be forced with order (
NPY_KEEPORDER
is recommended), and when dtype is specified, casting indicates how permissive the data conversion should be.See the
einsum
function for more details.

PyObject *PyArray_Correlate(PyObject *op1, PyObject *op2, int mode)#
Compute the 1d correlation of the 1d arrays op1 and op2 . The correlation is computed at each output point by multiplying op1 by a shifted version of op2 and summing the result. As a result of the shift, needed values outside of the defined range of op1 and op2 are interpreted as zero. The mode determines how many shifts to return: 0  return only shifts that did not need to assume zero values; 1  return an object that is the same size as op1, 2  return all possible shifts (any overlap at all is accepted).
Notes
This does not compute the usual correlation: if op2 is larger than op1, the arguments are swapped, and the conjugate is never taken for complex arrays. See PyArray_Correlate2 for the usual signal processing correlation.

PyObject *PyArray_Correlate2(PyObject *op1, PyObject *op2, int mode)#
Updated version of PyArray_Correlate, which uses the usual definition of correlation for 1d arrays. The correlation is computed at each output point by multiplying op1 by a shifted version of op2 and summing the result. As a result of the shift, needed values outside of the defined range of op1 and op2 are interpreted as zero. The mode determines how many shifts to return: 0  return only shifts that did not need to assume zero values; 1  return an object that is the same size as op1, 2  return all possible shifts (any overlap at all is accepted).
Notes
Compute z as follows:
z[k] = sum_n op1[n] * conj(op2[n+k])

PyObject *PyArray_Where(PyObject *condition, PyObject *x, PyObject *y)#
If both
x
andy
areNULL
, then returnPyArray_Nonzero
(condition). Otherwise, both x and y must be given and the object returned is shaped like condition and has elements of x and y where condition is respectively True or False.
Other functions#

npy_bool PyArray_CheckStrides(int elsize, int nd, npy_intp numbytes, npy_intp const *dims, npy_intp const *newstrides)#
Determine if newstrides is a strides array consistent with the memory of an nd dimensional array with shape
dims
and elementsize, elsize. The newstrides array is checked to see if jumping by the provided number of bytes in each direction will ever mean jumping more than numbytes which is the assumed size of the available memory segment. If numbytes is 0, then an equivalent numbytes is computed assuming nd, dims, and elsize refer to a singlesegment array. ReturnNPY_TRUE
if newstrides is acceptable, otherwise returnNPY_FALSE
.

int PyArray_MultiplyIntList(int const *seq, int n)#
Both of these routines multiply an n length array, seq, of integers and return the result. No overflow checking is performed.
Auxiliary data with object semantics#
New in version 1.7.0.

type NpyAuxData#
When working with more complex dtypes which are composed of other dtypes,
such as the struct dtype, creating inner loops that manipulate the dtypes
requires carrying along additional data. NumPy supports this idea
through a struct NpyAuxData
, mandating a few conventions so that
it is possible to do this.
Defining an NpyAuxData
is similar to defining a class in C++,
but the object semantics have to be tracked manually since the API is in C.
Here’s an example for a function which doubles up an element using
an element copier function as a primitive.
typedef struct {
NpyAuxData base;
ElementCopier_Func *func;
NpyAuxData *funcdata;
} eldoubler_aux_data;
void free_element_doubler_aux_data(NpyAuxData *data)
{
eldoubler_aux_data *d = (eldoubler_aux_data *)data;
/* Free the memory owned by this auxdata */
NPY_AUXDATA_FREE(d>funcdata);
PyArray_free(d);
}
NpyAuxData *clone_element_doubler_aux_data(NpyAuxData *data)
{
eldoubler_aux_data *ret = PyArray_malloc(sizeof(eldoubler_aux_data));
if (ret == NULL) {
return NULL;
}
/* Raw copy of all data */
memcpy(ret, data, sizeof(eldoubler_aux_data));
/* Fix up the owned auxdata so we have our own copy */
ret>funcdata = NPY_AUXDATA_CLONE(ret>funcdata);
if (ret>funcdata == NULL) {
PyArray_free(ret);
return NULL;
}
return (NpyAuxData *)ret;
}
NpyAuxData *create_element_doubler_aux_data(
ElementCopier_Func *func,
NpyAuxData *funcdata)
{
eldoubler_aux_data *ret = PyArray_malloc(sizeof(eldoubler_aux_data));
if (ret == NULL) {
PyErr_NoMemory();
return NULL;
}
memset(&ret, 0, sizeof(eldoubler_aux_data));
ret>base>free = &free_element_doubler_aux_data;
ret>base>clone = &clone_element_doubler_aux_data;
ret>func = func;
ret>funcdata = funcdata;
return (NpyAuxData *)ret;
}

type NpyAuxData_FreeFunc#
The function pointer type for NpyAuxData free functions.

type NpyAuxData_CloneFunc#
The function pointer type for NpyAuxData clone functions. These functions should never set the Python exception on error, because they may be called from a multithreaded context.

void NPY_AUXDATA_FREE(NpyAuxData *auxdata)#
A macro which calls the auxdata’s free function appropriately, does nothing if auxdata is NULL.

NpyAuxData *NPY_AUXDATA_CLONE(NpyAuxData *auxdata)#
A macro which calls the auxdata’s clone function appropriately, returning a deep copy of the auxiliary data.
Array iterators#
As of NumPy 1.6.0, these array iterators are superseded by
the new array iterator, NpyIter
.
An array iterator is a simple way to access the elements of an Ndimensional array quickly and efficiently, as seen in the example which provides more description of this useful approach to looping over an array from C.

PyObject *PyArray_IterNew(PyObject *arr)#
Return an array iterator object from the array, arr. This is equivalent to arr. flat. The array iterator object makes it easy to loop over an Ndimensional noncontiguous array in Cstyle contiguous fashion.

PyObject *PyArray_IterAllButAxis(PyObject *arr, int *axis)#
Return an array iterator that will iterate over all axes but the one provided in *axis. The returned iterator cannot be used with
PyArray_ITER_GOTO1D
. This iterator could be used to write something similar to what ufuncs do wherein the loop over the largest axis is done by a separate subroutine. If *axis is negative then *axis will be set to the axis having the smallest stride and that axis will be used.

PyObject *PyArray_BroadcastToShape(PyObject *arr, npy_intp const *dimensions, int nd)#
Return an array iterator that is broadcast to iterate as an array of the shape provided by dimensions and nd.

int PyArrayIter_Check(PyObject *op)#
Evaluates true if op is an array iterator (or instance of a subclass of the array iterator type).

void PyArray_ITER_NEXT(PyObject *iterator)#
Incremement the index and the dataptr members of the iterator to point to the next element of the array. If the array is not (Cstyle) contiguous, also increment the Ndimensional coordinates array.

void PyArray_ITER_GOTO(PyObject *iterator, npy_intp *destination)#
Set the iterator index, dataptr, and coordinates members to the location in the array indicated by the Ndimensional carray, destination, which must have size at least iterator >nd_m1+1.
Broadcasting (multiiterators)#

PyObject *PyArray_MultiIterNew(int num, ...)#
A simplified interface to broadcasting. This function takes the number of arrays to broadcast and then num extra (
PyObject *
) arguments. These arguments are converted to arrays and iterators are created.PyArray_Broadcast
is then called on the resulting multiiterator object. The resulting, broadcasted multiterator object is then returned. A broadcasted operation can then be performed using a single loop and usingPyArray_MultiIter_NEXT
(..)

void PyArray_MultiIter_RESET(PyObject *multi)#
Reset all the iterators to the beginning in a multiiterator object, multi.

void PyArray_MultiIter_NEXT(PyObject *multi)#
Advance each iterator in a multiiterator object, multi, to its next (broadcasted) element.

void *PyArray_MultiIter_DATA(PyObject *multi, int i)#
Return the datapointer of the i \(^{\textrm{th}}\) iterator in a multiiterator object.

void PyArray_MultiIter_NEXTi(PyObject *multi, int i)#
Advance the pointer of only the i \(^{\textrm{th}}\) iterator.

void PyArray_MultiIter_GOTO(PyObject *multi, npy_intp *destination)#
Advance each iterator in a multiiterator object, multi, to the given \(N\) dimensional destination where \(N\) is the number of dimensions in the broadcasted array.

void PyArray_MultiIter_GOTO1D(PyObject *multi, npy_intp index)#
Advance each iterator in a multiiterator object, multi, to the corresponding location of the index into the flattened broadcasted array.

int PyArray_MultiIter_NOTDONE(PyObject *multi)#
Evaluates TRUE as long as the multiiterator has not looped through all of the elements (of the broadcasted result), otherwise it evaluates FALSE.

npy_intp PyArray_MultiIter_SIZE(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns the total broadcasted size of a multiiterator object.

int PyArray_MultiIter_NDIM(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns the number of dimensions in the broadcasted result of a multiiterator object.

npy_intp PyArray_MultiIter_INDEX(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns the current (1d) index into the broadcasted result of a multiiterator object.

int PyArray_MultiIter_NUMITER(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns the number of iterators that are represented by a multiiterator object.

void **PyArray_MultiIter_ITERS(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns an array of iterator objects that holds the iterators for the arrays to be broadcast together. On return, the iterators are adjusted for broadcasting.

npy_intp *PyArray_MultiIter_DIMS(PyArrayMultiIterObject *multi)#
New in version 1.26.0.
Returns a pointer to the dimensions/shape of the broadcasted result of a multiiterator object.

int PyArray_Broadcast(PyArrayMultiIterObject *mit)#
This function encapsulates the broadcasting rules. The mit container should already contain iterators for all the arrays that need to be broadcast. On return, these iterators will be adjusted so that iteration over each simultaneously will accomplish the broadcasting. A negative number is returned if an error occurs.

int PyArray_RemoveSmallest(PyArrayMultiIterObject *mit)#
This function takes a multiiterator object that has been previously “broadcasted,” finds the dimension with the smallest “sum of strides” in the broadcasted result and adapts all the iterators so as not to iterate over that dimension (by effectively making them of length1 in that dimension). The corresponding dimension is returned unless mit >nd is 0, then 1 is returned. This function is useful for constructing ufunclike routines that broadcast their inputs correctly and then call a strided 1d version of the routine as the innerloop. This 1d version is usually optimized for speed and for this reason the loop should be performed over the axis that won’t require large stride jumps.
Neighborhood iterator#
New in version 1.4.0.
Neighborhood iterators are subclasses of the iterator object, and can be used to iter over a neighborhood of a point. For example, you may want to iterate over every voxel of a 3d image, and for every such voxel, iterate over an hypercube. Neighborhood iterator automatically handle boundaries, thus making this kind of code much easier to write than manual boundaries handling, at the cost of a slight overhead.

PyObject *PyArray_NeighborhoodIterNew(PyArrayIterObject *iter, npy_intp bounds, int mode, PyArrayObject *fill_value)#
This function creates a new neighborhood iterator from an existing iterator. The neighborhood will be computed relatively to the position currently pointed by iter, the bounds define the shape of the neighborhood iterator, and the mode argument the boundaries handling mode.
The bounds argument is expected to be a (2 * iter>ao>nd) arrays, such as the range bound[2*i]>bounds[2*i+1] defines the range where to walk for dimension i (both bounds are included in the walked coordinates). The bounds should be ordered for each dimension (bounds[2*i] <= bounds[2*i+1]).
The mode should be one of:

NPY_NEIGHBORHOOD_ITER_ZERO_PADDING#
Zero padding. Outside bounds values will be 0.

NPY_NEIGHBORHOOD_ITER_ONE_PADDING#
One padding, Outside bounds values will be 1.

NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING#
Constant padding. Outside bounds values will be the same as the first item in fill_value.

NPY_NEIGHBORHOOD_ITER_MIRROR_PADDING#
Mirror padding. Outside bounds values will be as if the array items were mirrored. For example, for the array [1, 2, 3, 4], x[2] will be 2, x[2] will be 1, x[4] will be 4, x[5] will be 1, etc…

NPY_NEIGHBORHOOD_ITER_CIRCULAR_PADDING#
Circular padding. Outside bounds values will be as if the array was repeated. For example, for the array [1, 2, 3, 4], x[2] will be 3, x[2] will be 4, x[4] will be 1, x[5] will be 2, etc…
If the mode is constant filling (
NPY_NEIGHBORHOOD_ITER_CONSTANT_PADDING
), fill_value should point to an array object which holds the filling value (the first item will be the filling value if the array contains more than one item). For other cases, fill_value may be NULL.The iterator holds a reference to iter
Return NULL on failure (in which case the reference count of iter is not changed)
iter itself can be a Neighborhood iterator: this can be useful for .e.g automatic boundaries handling
the object returned by this function should be safe to use as a normal iterator
If the position of iter is changed, any subsequent call to PyArrayNeighborhoodIter_Next is undefined behavior, and PyArrayNeighborhoodIter_Reset must be called.
If the position of iter is not the beginning of the data and the underlying data for iter is contiguous, the iterator will point to the start of the data instead of position pointed by iter. To avoid this situation, iter should be moved to the required position only after the creation of iterator, and PyArrayNeighborhoodIter_Reset must be called.
PyArrayIterObject *iter; PyArrayNeighborhoodIterObject *neigh_iter; iter = PyArray_IterNew(x); /*For a 3x3 kernel */ bounds = {1, 1, 1, 1}; neigh_iter = (PyArrayNeighborhoodIterObject*)PyArray_NeighborhoodIterNew( iter, bounds, NPY_NEIGHBORHOOD_ITER_ZERO_PADDING, NULL); for(i = 0; i < iter>size; ++i) { for (j = 0; j < neigh_iter>size; ++j) { /* Walk around the item currently pointed by iter>dataptr */ PyArrayNeighborhoodIter_Next(neigh_iter); } /* Move to the next point of iter */ PyArrayIter_Next(iter); PyArrayNeighborhoodIter_Reset(neigh_iter); }

NPY_NEIGHBORHOOD_ITER_ZERO_PADDING#

int PyArrayNeighborhoodIter_Reset(PyArrayNeighborhoodIterObject *iter)#
Reset the iterator position to the first point of the neighborhood. This should be called whenever the iter argument given at PyArray_NeighborhoodIterObject is changed (see example)

int PyArrayNeighborhoodIter_Next(PyArrayNeighborhoodIterObject *iter)#
After this call, iter>dataptr points to the next point of the neighborhood. Calling this function after every point of the neighborhood has been visited is undefined.
Array scalars#

PyObject *PyArray_Return(PyArrayObject *arr)#
This function steals a reference to arr.
This function checks to see if arr is a 0dimensional array and, if so, returns the appropriate array scalar. It should be used whenever 0dimensional arrays could be returned to Python.

PyObject *PyArray_Scalar(void *data, PyArray_Descr *dtype, PyObject *base)#
Return an array scalar object of the given dtype by copying from memory pointed to by data. base is expected to be the array object that is the owner of the data. base is required if dtype is a
void
scalar, or if theNPY_USE_GETITEM
flag is set and it is known that thegetitem
method uses thearr
argument without checking if it isNULL
. Otherwise base may beNULL
.If the data is not in native byte order (as indicated by
dtype>byteorder
) then this function will byteswap the data, because array scalars are always in correct machinebyte order.

PyObject *PyArray_ToScalar(void *data, PyArrayObject *arr)#
Return an array scalar object of the type and itemsize indicated by the array object arr copied from the memory pointed to by data and swapping if the data in arr is not in machine byteorder.

PyObject *PyArray_FromScalar(PyObject *scalar, PyArray_Descr *outcode)#
Return a 0dimensional array of type determined by outcode from scalar which should be an arrayscalar object. If outcode is NULL, then the type is determined from scalar.

void PyArray_ScalarAsCtype(PyObject *scalar, void *ctypeptr)#
Return in ctypeptr a pointer to the actual value in an array scalar. There is no error checking so scalar must be an arrayscalar object, and ctypeptr must have enough space to hold the correct type. For flexiblesized types, a pointer to the data is copied into the memory of ctypeptr, for all other types, the actual data is copied into the address pointed to by ctypeptr.

int PyArray_CastScalarToCtype(PyObject *scalar, void *ctypeptr, PyArray_Descr *outcode)#
Return the data (cast to the data type indicated by outcode) from the arrayscalar, scalar, into the memory pointed to by ctypeptr (which must be large enough to handle the incoming memory).
Returns 1 on failure, and 0 on success.

PyObject *PyArray_TypeObjectFromType(int type)#
Returns a scalar typeobject from a typenumber, type . Equivalent to
PyArray_DescrFromType
(type)>typeobj except for reference counting and errorchecking. Returns a new reference to the typeobject on success orNULL
on failure.

NPY_SCALARKIND PyArray_ScalarKind(int typenum, PyArrayObject **arr)#
See the function
PyArray_MinScalarType
for an alternative mechanism introduced in NumPy 1.6.0.Return the kind of scalar represented by typenum and the array in *arr (if arr is not
NULL
). The array is assumed to be rank0 and only used if typenum represents a signed integer. If arr is notNULL
and the first element is negative thenNPY_INTNEG_SCALAR
is returned, otherwiseNPY_INTPOS_SCALAR
is returned. The possible return values are the enumerated values inNPY_SCALARKIND
.

int PyArray_CanCoerceScalar(char thistype, char neededtype, NPY_SCALARKIND scalar)#
See the function
PyArray_ResultType
for details of NumPy type promotion, updated in NumPy 1.6.0.Implements the rules for scalar coercion. Scalars are only silently coerced from thistype to neededtype if this function returns nonzero. If scalar is
NPY_NOSCALAR
, then this function is equivalent toPyArray_CanCastSafely
. The rule is that scalars of the same KIND can be coerced into arrays of the same KIND. This rule means that highprecision scalars will never cause lowprecision arrays of the same KIND to be upcast.
Datatype descriptors#
Warning
Datatype objects must be reference counted so be aware of the action on the datatype reference of different CAPI calls. The standard rule is that when a datatype object is returned it is a new reference. Functions that take PyArray_Descr* objects and return arrays steal references to the datatype their inputs unless otherwise noted. Therefore, you must own a reference to any datatype object used as input to such a function.

int PyArray_DescrCheck(PyObject *obj)#
Evaluates as true if obj is a datatype object ( PyArray_Descr* ).

PyArray_Descr *PyArray_DescrNew(PyArray_Descr *obj)#
Return a new datatype object copied from obj (the fields reference is just updated so that the new object points to the same fields dictionary if any).

PyArray_Descr *PyArray_DescrNewFromType(int typenum)#
Create a new datatype object from the builtin (or userregistered) datatype indicated by typenum. All builtin types should not have any of their fields changed. This creates a new copy of the
PyArray_Descr
structure so that you can fill it in as appropriate. This function is especially needed for flexible datatypes which need to have a new elsize member in order to be meaningful in array construction.

PyArray_Descr *PyArray_DescrNewByteorder(PyArray_Descr *obj, char newendian)#
Create a new datatype object with the byteorder set according to newendian. All referenced datatype objects (in subdescr and fields members of the datatype object) are also changed (recursively).
The value of newendian is one of these macros:

NPY_IGNORE#

NPY_SWAP#

NPY_NATIVE#

NPY_LITTLE#

NPY_BIG#
If a byteorder of
NPY_IGNORE
is encountered it is left alone. If newendian isNPY_SWAP
, then all byteorders are swapped. Other valid newendian values areNPY_NATIVE
,NPY_LITTLE
, andNPY_BIG
which all cause the returned datatyped descriptor (and all it’s referenced datatype descriptors) to have the corresponding byte order.

PyArray_Descr *PyArray_DescrFromObject(PyObject *op, PyArray_Descr *mintype)#
Determine an appropriate datatype object from the object op (which should be a “nested” sequence object) and the minimum datatype descriptor mintype (which can be
NULL
). Similar in behavior to array(op).dtype. Don’t confuse this function withPyArray_DescrConverter
. This function essentially looks at all the objects in the (nested) sequence and determines the datatype from the elements it finds.

PyArray_Descr *PyArray_DescrFromScalar(PyObject *scalar)#
Return a datatype object from an arrayscalar object. No checking is done to be sure that scalar is an array scalar. If no suitable datatype can be determined, then a datatype of
NPY_OBJECT
is returned by default.

PyArray_Descr *PyArray_DescrFromType(int typenum)#
Returns a datatype object corresponding to typenum. The typenum can be one of the enumerated types, a character code for one of the enumerated types, or a userdefined type. If you want to use a flexible size array, then you need to
flexible typenum
and set the resultselsize
parameter to the desired size. The typenum is one of theNPY_TYPES
.

int PyArray_DescrConverter(PyObject *obj, PyArray_Descr **dtype)#
Convert any compatible Python object, obj, to a datatype object in dtype. A large number of Python objects can be converted to datatype objects. See Data type objects (dtype) for a complete description. This version of the converter converts None objects to a
NPY_DEFAULT_TYPE
datatype object. This function can be used with the “O&” character code inPyArg_ParseTuple
processing.

int PyArray_DescrConverter2(PyObject *obj, PyArray_Descr **dtype)#
Convert any compatible Python object, obj, to a datatype object in dtype. This version of the converter converts None objects so that the returned datatype is
NULL
. This function can also be used with the “O&” character in PyArg_ParseTuple processing.

int Pyarray_DescrAlignConverter(PyObject *obj, PyArray_Descr **dtype)#
Like
PyArray_DescrConverter
except it aligns Cstructlike objects on wordboundaries as the compiler would.

int Pyarray_DescrAlignConverter2(PyObject *obj, PyArray_Descr **dtype)#
Like
PyArray_DescrConverter2
except it aligns Cstructlike objects on wordboundaries as the compiler would.
Data Type Promotion and Inspection#

PyArray_DTypeMeta *PyArray_CommonDType(PyArray_DTypeMeta *dtype1, PyArray_DTypeMeta *dtype2)#
This function defines the common DType operator. Note that the common DType will not be
object
(unless one of the DTypes isobject
). Similar tonumpy.result_type
, but works on the classes and not instances.

PyArray_DTypeMeta *PyArray_PromoteDTypeSequence(npy_intp length, PyArray_DTypeMeta **dtypes_in)#
Promotes a list of DTypes with each other in a way that should guarantee stable results even when changing the order. This function is smarter and can often return successful and unambiguous results when
common_dtype(common_dtype(dt1, dt2), dt3)
would depend on the operation order or fail. Nevertheless, DTypes should aim to ensure that their commondtype implementation is associative and commutative! (Mainly, unsigned and signed integers are not.)For guaranteed consistent results DTypes must implement commonDtype “transitively”. If A promotes B and B promotes C, than A must generally also promote C; where “promotes” means implements the promotion. (There are some exceptions for abstract DTypes)
In general this approach always works as long as the most generic dtype is either strictly larger, or compatible with all other dtypes. For example promoting
float16
with any other float, integer, or unsigned integer again gives a floating point number.

PyArray_Descr *PyArray_GetDefaultDescr(PyArray_DTypeMeta *DType)#
Given a DType class, returns the default instance (descriptor). This checks for a
singleton
first and only calls thedefault_descr
function if necessary.
Custom Data Types#
New in version 2.0.
These functions allow defining custom flexible data types outside of NumPy. See
NEP 42 for more details about the rationale and design of the new
DType system. See the numpyuserdtypes repository for a number of example DTypes.
Also see PyArray_DTypeMeta and PyArrayDTypeMeta_Spec for documentation on PyArray_DTypeMeta
and
PyArrayDTypeMeta_Spec
.

int PyArrayInitDTypeMeta_FromSpec(PyArray_DTypeMeta *Dtype, PyArrayDTypeMeta_Spec *spec)#
Initialize a new DType. It must currently be a static Python C type that is declared as
PyArray_DTypeMeta
and notPyTypeObject
. Further, it must subclass np.dtype and set its type toPyArrayDTypeMeta_Type
(before callingPyType_Ready
), which has additional fields compared to a normalPyTypeObject
. See the examples in thenumpyuserdtypes
repository for usage with both parametric and nonparametric data types.
Flags#
Flags that can be set on the PyArrayDTypeMeta_Spec
to initialize the DType.

NPY_DT_ABSTRACT#
Indicates the DType is an abstract “base” DType in a DType hierarchy and should not be directly instantiated.

NPY_DT_PARAMETRIC#
Indicates the DType is parametric and does not have a unique singleton instance.

NPY_DT_NUMERIC#
Indicates the DType represents a numerical value.
Slot IDs and API Function Typedefs#
These IDs correspond to slots in the DType API and are used to identify
implementations of each slot from the items of the slots
array
member of PyArrayDTypeMeta_Spec
struct.

NPY_DT_discover_descr_from_pyobject#

typedef PyArray_Descr *(PyArrayDTypeMeta_DiscoverDescrFromPyobject)(PyArray_DTypeMeta *cls, PyObject *obj)#
Used during DType inference to find the correct DType for a given PyObject. Must return a descriptor instance appropriate to store the data in the python object that is passed in. obj is the python object to inspect and cls is the DType class to create a descriptor for.

NPY_DT_default_descr#

typedef PyArray_Descr *(PyArrayDTypeMeta_DefaultDescriptor)(PyArray_DTypeMeta *cls)#
Returns the default descriptor instance for the DType. Must be defined for parametric data types. Nonparametric data types return the singleton by default.

NPY_DT_common_dtype#

typedef PyArray_DTypeMeta *(PyArrayDTypeMeta_CommonDType)(PyArray_DTypeMeta *dtype1, PyArray_DTypeMeta *dtype2)#
Given two input DTypes, determines the appropriate “common” DType that can store values for both types. Returns
Py_NotImplemented
if no such type exists.

NPY_DT_common_instance#

typedef PyArray_Descr *(PyArrayDTypeMeta_CommonInstance)(PyArray_Descr *dtype1, PyArray_Descr *dtype2)#
Given two input descriptors, determines the appropriate “common” descriptor that can store values for both instances. Returns
NULL
on error.

NPY_DT_ensure_canonical#

typedef PyArray_Descr *(PyArrayDTypeMeta_EnsureCanonical)(PyArray_Descr *dtype)#
Returns the “canonical” representation for a descriptor instance. The notion of a canonical descriptor generalizes the concept of byte order, in that a canonical descriptor always has native byte order. If the descriptor is already canonical, this function returns a new reference to the input descriptor.

NPY_DT_setitem#

typedef int (PyArrayDTypeMeta_SetItem)(PyArray_Descr*, PyObject*, char*)#
Implements scalar setitem for an array element given a PyObject.

NPY_DT_getitem#

typedef PyObject *(PyArrayDTypeMeta_GetItem)(PyArray_Descr*, char*)#
Implements scalar getitem for an array element. Must return a python scalar.

NPY_DT_get_clear_loop#
If defined, sets a traversal loop that clears data in the array. This is most useful for arrays of references that must clean up array entries before the array is garbage collected. Implements
PyArrayMethod_GetTraverseLoop
.

NPY_DT_get_fill_zero_loop#
If defined, sets a traversal loop that fills an array with “zero” values, which may have a DTypespecific meaning. This is called inside
numpy.zeros
for arrays that need to write a custom sentinel value that represents zero if for some reason a zerofilled array is not sufficient. ImplementsPyArrayMethod_GetTraverseLoop
.

NPY_DT_finalize_descr#

typedef PyArray_Descr *(PyArrayDTypeMeta_FinalizeDescriptor)(PyArray_Descr *dtype)#
If defined, a function that is called to “finalize” a descriptor instance after an array is created. One use of this function is to force newly created arrays to have a newly created descriptor instance, no matter what input descriptor is provided by a user.
PyArray_ArrFuncs slots#
In addition the above slots, the following slots are exposed to allow
filling the PyArray_ArrFuncs struct attached to descriptor
instances. Note that in the future these will be replaced by proper
DType API slots but for now we have exposed the legacy
PyArray_ArrFuncs
slots.

NPY_DT_PyArray_ArrFuncs_getitem#
Allows setting a perdtype getitem. Note that this is not necessary to define unless the default version calling the function defined with the
NPY_DT_getitem
ID is unsuitable. This version will be slightly faster than usingNPY_DT_getitem
at the cost of sometimes needing to deal with a NULL input array.

NPY_DT_PyArray_ArrFuncs_setitem#
Allows setting a perdtype setitem. Note that this is not necessary to define unless the default version calling the function defined with the
NPY_DT_setitem
ID is unsuitable for some reason.

NPY_DT_PyArray_ArrFuncs_compare#
Computes a comparison for
numpy.sort
, implementsPyArray_CompareFunc
.

NPY_DT_PyArray_ArrFuncs_argmax#
Computes the argmax for
numpy.argmax
, implementsPyArray_ArgFunc
.

NPY_DT_PyArray_ArrFuncs_argmin#
Computes the argmin for
numpy.argmin
, implementsPyArray_ArgFunc
.

NPY_DT_PyArray_ArrFuncs_dotfunc#
Computes the dot product for
numpy.dot
, implementsPyArray_DotFunc
.

NPY_DT_PyArray_ArrFuncs_scanfunc#
A formatted input function for
numpy.fromfile
, implementsPyArray_ScanFunc
.

NPY_DT_PyArray_ArrFuncs_fromstr#
A string parsing function for
numpy.fromstring
, implementsPyArray_FromStrFunc
.

NPY_DT_PyArray_ArrFuncs_nonzero#
Computes the nonzero function for
numpy.nonzero
, implementsPyArray_NonzeroFunc
.

NPY_DT_PyArray_ArrFuncs_fill#
An array filling function for
numpy.ndarray.fill
, implementsPyArray_FillFunc
.

NPY_DT_PyArray_ArrFuncs_fillwithscalar#
A function to fill an array with a scalar value for
numpy.ndarray.fill
, implementsPyArray_FillWithScalarFunc
.

NPY_DT_PyArray_ArrFuncs_sort#
An array of PyArray_SortFunc of length
NPY_NSORTS
. If set, allows defining custom sorting implementations for each of the sorting algorithms numpy implements.

NPY_DT_PyArray_ArrFuncs_argsort#
An array of PyArray_ArgSortFunc of length
NPY_NSORTS
. If set, allows defining custom argsorting implementations for each of the sorting algorithms numpy implements.
Macros and Static Inline Functions#
These macros and static inline functions are provided to allow more
understandable and idiomatic code when working with PyArray_DTypeMeta
instances.

NPY_DTYPE(descr)#
Returns a
PyArray_DTypeMeta *
pointer to the DType of a given descriptor instance.

static inline PyArray_DTypeMeta *NPY_DT_NewRef(PyArray_DTypeMeta *o)#
Returns a
PyArray_DTypeMeta *
pointer to a new reference to a DType.
Conversion utilities#
For use with PyArg_ParseTuple
#
All of these functions can be used in PyArg_ParseTuple
(…) with
the “O&” format specifier to automatically convert any Python object
to the required Cobject. All of these functions return
NPY_SUCCEED
if successful and NPY_FAIL
if not. The first
argument to all of these function is a Python object. The second
argument is the address of the Ctype to convert the Python object
to.
Warning
Be sure to understand what steps you should take to manage the memory when using these conversion functions. These functions can require freeing memory, and/or altering the reference counts of specific objects based on your use.

int PyArray_Converter(PyObject *obj, PyObject **address)#
Convert any Python object to a
PyArrayObject
. IfPyArray_Check
(obj) is TRUE then its reference count is incremented and a reference placed in address. If obj is not an array, then convert it to an array usingPyArray_FromAny
. No matter what is returned, you must DECREF the object returned by this routine in address when you are done with it.

int PyArray_OutputConverter(PyObject *obj, PyArrayObject **address)#
This is a default converter for output arrays given to functions. If obj is
Py_None
orNULL
, then *address will beNULL
but the call will succeed. IfPyArray_Check
( obj) is TRUE then it is returned in *address without incrementing its reference count.

int PyArray_IntpConverter(PyObject *obj, PyArray_Dims *seq)#
Convert any Python sequence, obj, smaller than
NPY_MAXDIMS
to a Carray ofnpy_intp
. The Python object could also be a single number. The seq variable is a pointer to a structure with members ptr and len. On successful return, seq >ptr contains a pointer to memory that must be freed, by callingPyDimMem_FREE
, to avoid a memory leak. The restriction on memory size allows this converter to be conveniently used for sequences intended to be interpreted as array shapes.

int PyArray_BufferConverter(PyObject *obj, PyArray_Chunk *buf)#
Convert any Python object, obj, with a (singlesegment) buffer interface to a variable with members that detail the object’s use of its chunk of memory. The buf variable is a pointer to a structure with base, ptr, len, and flags members. The
PyArray_Chunk
structure is binary compatible with the Python’s buffer object (through its len member on 32bit platforms and its ptr member on 64bit platforms). On return, the base member is set to obj (or its base if obj is already a buffer object pointing to another object). If you need to hold on to the memory be sure to INCREF the base member. The chunk of memory is pointed to by buf >ptr member and has length buf >len. The flags member of buf isNPY_ARRAY_ALIGNED
with theNPY_ARRAY_WRITEABLE
flag set if obj has a writeable buffer interface.

int PyArray_AxisConverter(PyObject *obj, int *axis)#
Convert a Python object, obj, representing an axis argument to the proper value for passing to the functions that take an integer axis. Specifically, if obj is None, axis is set to
NPY_RAVEL_AXIS
which is interpreted correctly by the CAPI functions that take axis arguments.

int PyArray_BoolConverter(PyObject *obj, npy_bool *value)#
Convert any Python object, obj, to
NPY_TRUE
orNPY_FALSE
, and place the result in value.

int PyArray_ByteorderConverter(PyObject *obj, char *endian)#
Convert Python strings into the corresponding byteorder character: ‘>’, ‘<’, ‘s’, ‘=’, or ‘’.

int PyArray_SortkindConverter(PyObject *obj, NPY_SORTKIND *sort)#
Convert Python strings into one of
NPY_QUICKSORT
(starts with ‘q’ or ‘Q’),NPY_HEAPSORT
(starts with ‘h’ or ‘H’),NPY_MERGESORT
(starts with ‘m’ or ‘M’) orNPY_STABLESORT
(starts with ‘t’ or ‘T’).NPY_MERGESORT
andNPY_STABLESORT
are aliased to each other for backwards compatibility and may refer to one of several stable sorting algorithms depending on the data type.

int PyArray_SearchsideConverter(PyObject *obj, NPY_SEARCHSIDE *side)#
Convert Python strings into one of
NPY_SEARCHLEFT
(starts with ‘l’ or ‘L’), orNPY_SEARCHRIGHT
(starts with ‘r’ or ‘R’).

int PyArray_OrderConverter(PyObject *obj, NPY_ORDER *order)#
Convert the Python strings ‘C’, ‘F’, ‘A’, and ‘K’ into the
NPY_ORDER
enumerationNPY_CORDER
,NPY_FORTRANORDER
,NPY_ANYORDER
, andNPY_KEEPORDER
.

int PyArray_CastingConverter(PyObject *obj, NPY_CASTING *casting)#
Convert the Python strings ‘no’, ‘equiv’, ‘safe’, ‘same_kind’, and ‘unsafe’ into the
NPY_CASTING
enumerationNPY_NO_CASTING
,NPY_EQUIV_CASTING
,NPY_SAFE_CASTING
,NPY_SAME_KIND_CASTING
, andNPY_UNSAFE_CASTING
.

int PyArray_ClipmodeConverter(PyObject *object, NPY_CLIPMODE *val)#
Convert the Python strings ‘clip’, ‘wrap’, and ‘raise’ into the
NPY_CLIPMODE
enumerationNPY_CLIP
,NPY_WRAP
, andNPY_RAISE
.

int PyArray_ConvertClipmodeSequence(PyObject *object, NPY_CLIPMODE *modes, int n)#
Converts either a sequence of clipmodes or a single clipmode into a C array of
NPY_CLIPMODE
values. The number of clipmodes n must be known before calling this function. This function is provided to help functions allow a different clipmode for each dimension.
Other conversions#

int PyArray_PyIntAsInt(PyObject *op)#
Convert all kinds of Python objects (including arrays and array scalars) to a standard integer. On error, 1 is returned and an exception set. You may find useful the macro:
#define error_converting(x) (((x) == 1) && PyErr_Occurred())

npy_intp PyArray_PyIntAsIntp(PyObject *op)#
Convert all kinds of Python objects (including arrays and array scalars) to a (platformpointersized) integer. On error, 1 is returned and an exception set.

int PyArray_IntpFromSequence(PyObject *seq, npy_intp *vals, int maxvals)#
Convert any Python sequence (or single Python number) passed in as seq to (up to) maxvals pointersized integers and place them in the vals array. The sequence can be smaller then maxvals as the number of converted objects is returned.
Miscellaneous#
Importing the API#
In order to make use of the CAPI from another extension module, the
import_array
function must be called. If the extension module is
selfcontained in a single .c file, then that is all that needs to be
done. If, however, the extension module involves multiple files where
the CAPI is needed then some additional steps must be taken.

int PyArray_ImportNumPyAPI(void)#
Ensures that the NumPy CAPI is imported and usable. It returns
0
on success and1
with an error set if NumPy couldn’t be imported. While preferable to call it once at module initialization, this function is very lightweight if called multiple times.New in version 2.0: This function is backported in the
npy_2_compat.h
header.

import_array(void)#
This function must be called in the initialization section of a module that will make use of the CAPI. It imports the module where the functionpointer table is stored and points the correct variable to it.

PY_ARRAY_UNIQUE_SYMBOL#

NO_IMPORT_ARRAY#
Using these #defines you can use the CAPI in multiple files for a single extension module. In each file you must define
PY_ARRAY_UNIQUE_SYMBOL
to some name that will hold the CAPI (e.g. myextension_ARRAY_API). This must be done before including the numpy/arrayobject.h file. In the module initialization routine you callimport_array
. In addition, in the files that do not have the module initialization sub_routine defineNO_IMPORT_ARRAY
prior to including numpy/arrayobject.h.Suppose I have two files coolmodule.c and coolhelper.c which need to be compiled and linked into a single extension module. Suppose coolmodule.c contains the required initcool module initialization function (with the import_array() function called). Then, coolmodule.c would have at the top:
#define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API #include numpy/arrayobject.h
On the other hand, coolhelper.c would contain at the top:
#define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL cool_ARRAY_API #include numpy/arrayobject.h
You can also put the common two last lines into an extensionlocal header file as long as you make sure that NO_IMPORT_ARRAY is #defined before #including that file.
Internally, these #defines work as follows:
If neither is defined, the CAPI is declared to be
static void**
, so it is only visible within the compilation unit that #includes numpy/arrayobject.h.If
PY_ARRAY_UNIQUE_SYMBOL
is #defined, butNO_IMPORT_ARRAY
is not, the CAPI is declared to bevoid**
, so that it will also be visible to other compilation units.If
NO_IMPORT_ARRAY
is #defined, regardless of whetherPY_ARRAY_UNIQUE_SYMBOL
is, the CAPI is declared to beextern void**
, so it is expected to be defined in another compilation unit.Whenever
PY_ARRAY_UNIQUE_SYMBOL
is #defined, it also changes the name of the variable holding the CAPI, which defaults toPyArray_API
, to whatever the macro is #defined to.
Checking the API Version#
Because python extensions are not used in the same way as usual libraries on
most platforms, some errors cannot be automatically detected at build time or
even runtime. For example, if you build an extension using a function available
only for numpy >= 1.3.0, and you import the extension later with numpy 1.2, you
will not get an import error (but almost certainly a segmentation fault when
calling the function). That’s why several functions are provided to check for
numpy versions. The macros NPY_VERSION
and
NPY_FEATURE_VERSION
corresponds to the numpy version used to build the
extension, whereas the versions returned by the functions
PyArray_GetNDArrayCVersion
and PyArray_GetNDArrayCFeatureVersion
corresponds to the runtime numpy’s version.
The rules for ABI and API compatibilities can be summarized as follows:
Whenever
NPY_VERSION
!=PyArray_GetNDArrayCVersion()
, the extension has to be recompiled (ABI incompatibility).NPY_VERSION
==PyArray_GetNDArrayCVersion()
andNPY_FEATURE_VERSION
<=PyArray_GetNDArrayCFeatureVersion()
means backward compatible changes.
ABI incompatibility is automatically detected in every numpy’s version. API
incompatibility detection was added in numpy 1.4.0. If you want to supported
many different numpy versions with one extension binary, you have to build your
extension with the lowest NPY_FEATURE_VERSION
as possible.

NPY_VERSION#
The current version of the ndarray object (check to see if this variable is defined to guarantee the
numpy/arrayobject.h
header is being used).

NPY_FEATURE_VERSION#
The current version of the CAPI.

unsigned int PyArray_GetNDArrayCVersion(void)#
This just returns the value
NPY_VERSION
.NPY_VERSION
changes whenever a backward incompatible change at the ABI level. Because it is in the CAPI, however, comparing the output of this function from the value defined in the current header gives a way to test if the CAPI has changed thus requiring a recompilation of extension modules that use the CAPI. This is automatically checked in the functionimport_array
.

unsigned int PyArray_GetNDArrayCFeatureVersion(void)#
New in version 1.4.0.
This just returns the value
NPY_FEATURE_VERSION
.NPY_FEATURE_VERSION
changes whenever the API changes (e.g. a function is added). A changed value does not always require a recompile.
Internal Flexibility#

void PyArray_SetStringFunction(PyObject *op, int repr)#
This function allows you to alter the tp_str and tp_repr methods of the array object to any Python function. Thus you can alter what happens for all arrays when str(arr) or repr(arr) is called from Python. The function to be called is passed in as op. If repr is nonzero, then this function will be called in response to repr(arr), otherwise the function will be called in response to str(arr). No check on whether or not op is callable is performed. The callable passed in to op should expect an array argument and should return a string to be printed.
Memory management#

char *PyDataMem_NEW(size_t nbytes)#

void PyDataMem_FREE(char *ptr)#

char *PyDataMem_RENEW(void *ptr, size_t newbytes)#
Macros to allocate, free, and reallocate memory. These macros are used internally to create arrays.

void PyDimMem_FREE(char *ptr)#

npy_intp *PyDimMem_RENEW(void *ptr, size_t newnd)#
Macros to allocate, free, and reallocate dimension and strides memory.

void *PyArray_malloc(size_t nbytes)#

void PyArray_free(void *ptr)#

void *PyArray_realloc(npy_intp *ptr, size_t nbytes)#
These macros use different memory allocators, depending on the constant
NPY_USE_PYMEM
. The system malloc is used whenNPY_USE_PYMEM
is 0, ifNPY_USE_PYMEM
is 1, then the Python memory allocator is used.
NPY_USE_PYMEM#

NPY_USE_PYMEM#

int PyArray_ResolveWritebackIfCopy(PyArrayObject *obj)#
If
obj>flags
hasNPY_ARRAY_WRITEBACKIFCOPY
, this function clears the flags, DECREF s obj>base and makes it writeable, and setsobj>base
to NULL. It then copiesobj>data
to obj>base>data, and returns the error state of the copy operation. This is the opposite ofPyArray_SetWritebackIfCopyBase
. Usually this is called once you are finished withobj
, just beforePy_DECREF(obj)
. It may be called multiple times, or withNULL
input. See alsoPyArray_DiscardWritebackIfCopy
.Returns 0 if nothing was done, 1 on error, and 1 if action was taken.
Threading support#
These macros are only meaningful if NPY_ALLOW_THREADS
evaluates True during compilation of the extension module. Otherwise,
these macros are equivalent to whitespace. Python uses a single Global
Interpreter Lock (GIL) for each Python process so that only a single
thread may execute at a time (even on multicpu machines). When
calling out to a compiled function that may take time to compute (and
does not have sideeffects for other threads like updated global
variables), the GIL should be released so that other Python threads
can run while the timeconsuming calculations are performed. This can
be accomplished using two groups of macros. Typically, if one macro in
a group is used in a code block, all of them must be used in the same
code block. Currently, NPY_ALLOW_THREADS
is defined to the
pythondefined WITH_THREADS
constant unless the environment
variable NPY_NOSMP
is set in which case
NPY_ALLOW_THREADS
is defined to be 0.

NPY_ALLOW_THREADS#

WITH_THREADS#
Group 1#
This group is used to call code that may take some time but does not use any Python CAPI calls. Thus, the GIL should be released during its calculation.

NPY_BEGIN_ALLOW_THREADS#
Equivalent to
Py_BEGIN_ALLOW_THREADS
except it usesNPY_ALLOW_THREADS
to determine if the macro if replaced with whitespace or not.

NPY_END_ALLOW_THREADS#
Equivalent to
Py_END_ALLOW_THREADS
except it usesNPY_ALLOW_THREADS
to determine if the macro if replaced with whitespace or not.

NPY_BEGIN_THREADS_DEF#
Place in the variable declaration area. This macro sets up the variable needed for storing the Python state.

NPY_BEGIN_THREADS#
Place right before code that does not need the Python interpreter (no Python CAPI calls). This macro saves the Python state and releases the GIL.

NPY_END_THREADS#
Place right after code that does not need the Python interpreter. This macro acquires the GIL and restores the Python state from the saved variable.

void NPY_BEGIN_THREADS_DESCR(PyArray_Descr *dtype)#
Useful to release the GIL only if dtype does not contain arbitrary Python objects which may need the Python interpreter during execution of the loop.

void NPY_END_THREADS_DESCR(PyArray_Descr *dtype)#
Useful to regain the GIL in situations where it was released using the BEGIN form of this macro.

void NPY_BEGIN_THREADS_THRESHOLDED(int loop_size)#
Useful to release the GIL only if loop_size exceeds a minimum threshold, currently set to 500. Should be matched with a
NPY_END_THREADS
to regain the GIL.
Group 2#
This group is used to reacquire the Python GIL after it has been released. For example, suppose the GIL has been released (using the previous calls), and then some path in the code (perhaps in a different subroutine) requires use of the Python CAPI, then these macros are useful to acquire the GIL. These macros accomplish essentially a reverse of the previous three (acquire the LOCK saving what state it had) and then rerelease it with the saved state.

NPY_ALLOW_C_API_DEF#
Place in the variable declaration area to set up the necessary variable.

NPY_ALLOW_C_API#
Place before code that needs to call the Python CAPI (when it is known that the GIL has already been released).

NPY_DISABLE_C_API#
Place after code that needs to call the Python CAPI (to rerelease the GIL).
Tip
Never use semicolons after the threading support macros.
Priority#

NPY_PRIORITY#
Default priority for arrays.

NPY_SUBTYPE_PRIORITY#
Default subtype priority.

NPY_SCALAR_PRIORITY#
Default scalar priority (very small)

double PyArray_GetPriority(PyObject *obj, double def)#
Return the
__array_priority__
attribute (converted to a double) of obj or def if no attribute of that name exists. Fast returns that avoid the attribute lookup are provided for objects of typePyArray_Type
.
Default buffers#

NPY_BUFSIZE#
Default size of the usersettable internal buffers.

NPY_MIN_BUFSIZE#
Smallest size of usersettable internal buffers.

NPY_MAX_BUFSIZE#
Largest size allowed for the usersettable buffers.
Other constants#

NPY_NUM_FLOATTYPE#
The number of floatingpoint types

NPY_MAXDIMS#
The maximum number of dimensions that may be used by NumPy. This is set to 64 and was 32 before NumPy 2.
Note
We encourage you to avoid
NPY_MAXDIMS
. A future version of NumPy may wish to remove any dimension limitation (and thus the constant). The limitation was created so that NumPy can use stack allocations internally for scratch space.If your algorithm has a reasonable maximum number of dimension you could check and use that locally.

NPY_MAXARGS#
The maximum number of array arguments that can be used in some functions. This used to be 32 before NumPy 2 and is now 64. To continue to allow using it as a check whether a number of arguments is compatible ufuncs, this macro is now runtime dependent.
Note
We discourage any use of
NPY_MAXARGS
that isn’t explicitly tied to checking for known NumPy limitations.

NPY_FALSE#
Defined as 0 for use with Bool.

NPY_TRUE#
Defined as 1 for use with Bool.

NPY_FAIL#
The return value of failed converter functions which are called using the “O&” syntax in
PyArg_ParseTuple
like functions.

NPY_SUCCEED#
The return value of successful converter functions which are called using the “O&” syntax in
PyArg_ParseTuple
like functions.

NPY_RAVEL_AXIS#
Some NumPy functions (mainly the Centrypoints for Python functions) have an
axis
argument. This macro may be passed foraxis=None
.Note
This macro is NumPy version dependent at runtime. The value is now the minimum integer. However, on NumPy 1.x
NPY_MAXDIMS
was used (at the time set to 32).
Miscellaneous Macros#

int PyArray_SAMESHAPE(PyArrayObject *a1, PyArrayObject *a2)#
Evaluates as True if arrays a1 and a2 have the same shape.

PyArray_MAX(a, b)#
Returns the maximum of a and b. If (a) or (b) are expressions they are evaluated twice.

PyArray_MIN(a, b)#
Returns the minimum of a and b. If (a) or (b) are expressions they are evaluated twice.

void PyArray_DiscardWritebackIfCopy(PyArrayObject *obj)#
If
obj>flags
hasNPY_ARRAY_WRITEBACKIFCOPY
, this function clears the flags, DECREF s obj>base and makes it writeable, and setsobj>base
to NULL. In contrast toPyArray_ResolveWritebackIfCopy
it makes no attempt to copy the data from obj>base. This undoesPyArray_SetWritebackIfCopyBase
. Usually this is called after an error when you are finished withobj
, just beforePy_DECREF(obj)
. It may be called multiple times, or withNULL
input.
Enumerated Types#

enum NPY_SORTKIND#
A special variabletype which can take on different values to indicate the sorting algorithm being used.

enumerator NPY_QUICKSORT#

enumerator NPY_HEAPSORT#

enumerator NPY_MERGESORT#

enumerator NPY_STABLESORT#
Used as an alias of
NPY_MERGESORT
and vice versa.

enumerator NPY_NSORTS#
Defined to be the number of sorts. It is fixed at three by the need for backwards compatibility, and consequently
NPY_MERGESORT
andNPY_STABLESORT
are aliased to each other and may refer to one of several stable sorting algorithms depending on the data type.

enumerator NPY_QUICKSORT#

enum NPY_SCALARKIND#
A special variable type indicating the number of “kinds” of scalars distinguished in determining scalarcoercion rules. This variable can take on the values:

enumerator NPY_NOSCALAR#

enumerator NPY_BOOL_SCALAR#

enumerator NPY_INTPOS_SCALAR#

enumerator NPY_INTNEG_SCALAR#

enumerator NPY_FLOAT_SCALAR#

enumerator NPY_COMPLEX_SCALAR#

enumerator NPY_OBJECT_SCALAR#

enumerator NPY_NSCALARKINDS#
Defined to be the number of scalar kinds (not including
NPY_NOSCALAR
).

enumerator NPY_NOSCALAR#

enum NPY_ORDER#
An enumeration type indicating the element order that an array should be interpreted in. When a brand new array is created, generally only NPY_CORDER and NPY_FORTRANORDER are used, whereas when one or more inputs are provided, the order can be based on them.

enumerator NPY_ANYORDER#
Fortran order if all the inputs are Fortran, C otherwise.

enumerator NPY_CORDER#
C order.

enumerator NPY_FORTRANORDER#
Fortran order.

enumerator NPY_KEEPORDER#
An order as close to the order of the inputs as possible, even if the input is in neither C nor Fortran order.

enumerator NPY_ANYORDER#

enum NPY_CLIPMODE#
A variable type indicating the kind of clipping that should be applied in certain functions.

enumerator NPY_RAISE#
The default for most operations, raises an exception if an index is out of bounds.

enumerator NPY_CLIP#
Clips an index to the valid range if it is out of bounds.

enumerator NPY_WRAP#
Wraps an index to the valid range if it is out of bounds.

enumerator NPY_RAISE#

enum NPY_SEARCHSIDE#
A variable type indicating whether the index returned should be that of the first suitable location (if
NPY_SEARCHLEFT
) or of the last (ifNPY_SEARCHRIGHT
).
enumerator NPY_SEARCHLEFT#

enumerator NPY_SEARCHRIGHT#

enumerator NPY_SEARCHLEFT#

enum NPY_SELECTKIND#
A variable type indicating the selection algorithm being used.

enumerator NPY_INTROSELECT#

enumerator NPY_INTROSELECT#

enum NPY_CASTING#
New in version 1.6.
An enumeration type indicating how permissive data conversions should be. This is used by the iterator added in NumPy 1.6, and is intended to be used more broadly in a future version.

enumerator NPY_NO_CASTING#
Only allow identical types.

enumerator NPY_EQUIV_CASTING#
Allow identical and casts involving byte swapping.

enumerator NPY_SAFE_CASTING#
Only allow casts which will not cause values to be rounded, truncated, or otherwise changed.

enumerator NPY_SAME_KIND_CASTING#
Allow any safe casts, and casts between types of the same kind. For example, float64 > float32 is permitted with this rule.

enumerator NPY_UNSAFE_CASTING#
Allow any cast, no matter what kind of data loss may occur.

enumerator NPY_NO_CASTING#