MCPcopy Create free account
hub / github.com/numpy/numpy / array_toscalar

Function array_toscalar

numpy/core/src/multiarray/methods.c:702–766  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

700}
701
702static PyObject *
703array_toscalar(PyArrayObject *self, PyObject *args)
704{
705 npy_intp multi_index[NPY_MAXDIMS];
706 int n = PyTuple_GET_SIZE(args);
707 int idim, ndim = PyArray_NDIM(self);
708
709 /* If there is a tuple as a single argument, treat it as the argument */
710 if (n == 1 && PyTuple_Check(PyTuple_GET_ITEM(args, 0))) {
711 args = PyTuple_GET_ITEM(args, 0);
712 n = PyTuple_GET_SIZE(args);
713 }
714
715 if (n == 0) {
716 if (PyArray_SIZE(self) == 1) {
717 for (idim = 0; idim < ndim; ++idim) {
718 multi_index[idim] = 0;
719 }
720 }
721 else {
722 PyErr_SetString(PyExc_ValueError,
723 "can only convert an array of size 1 to a Python scalar");
724 return NULL;
725 }
726 }
727 /* Special case of C-order flat indexing... :| */
728 else if (n == 1 && ndim != 1) {
729 npy_intp *shape = PyArray_SHAPE(self);
730 npy_intp value, size = PyArray_SIZE(self);
731
732 value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, 0));
733 if (error_converting(value)) {
734 return NULL;
735 }
736
737 if (check_and_adjust_index(&value, size, -1, NULL) < 0) {
738 return NULL;
739 }
740
741 /* Convert the flat index into a multi-index */
742 for (idim = ndim-1; idim >= 0; --idim) {
743 multi_index[idim] = value % shape[idim];
744 value /= shape[idim];
745 }
746 }
747 /* A multi-index tuple */
748 else if (n == ndim) {
749 npy_intp value;
750
751 for (idim = 0; idim < ndim; ++idim) {
752 value = PyArray_PyIntAsIntp(PyTuple_GET_ITEM(args, idim));
753 if (error_converting(value)) {
754 return NULL;
755 }
756 multi_index[idim] = value;
757 }
758 }
759 else {

Callers

nothing calls this directly

Calls 5

PyArray_NDIMFunction · 0.85
PyArray_SHAPEFunction · 0.85
PyArray_PyIntAsIntpFunction · 0.85
check_and_adjust_indexFunction · 0.85

Tested by

no test coverage detected