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

Function PyArray_FromScalar

numpy/core/src/multiarray/scalarapi.c:236–304  ·  view source on GitHub ↗

NUMPY_API * Get 0-dim array from scalar * * 0-dim array from array-scalar object * always contains a copy of the data * unless outcode is NULL, it is of void type and the referrer does * not own it either. * * steals reference to outcode */

Source from the content-addressed store, hash-verified

234 * steals reference to outcode
235 */
236NPY_NO_EXPORT PyObject *
237PyArray_FromScalar(PyObject *scalar, PyArray_Descr *outcode)
238{
239 /* convert to 0-dim array of scalar typecode */
240 PyArray_Descr *typecode = PyArray_DescrFromScalar(scalar);
241 if (typecode == NULL) {
242 Py_XDECREF(outcode);
243 return NULL;
244 }
245 if ((typecode->type_num == NPY_VOID) &&
246 !(((PyVoidScalarObject *)scalar)->flags & NPY_ARRAY_OWNDATA) &&
247 outcode == NULL) {
248 return PyArray_NewFromDescrAndBase(
249 &PyArray_Type, typecode,
250 0, NULL, NULL,
251 ((PyVoidScalarObject *)scalar)->obval,
252 ((PyVoidScalarObject *)scalar)->flags,
253 NULL, (PyObject *)scalar);
254 }
255
256 PyArrayObject *r = (PyArrayObject *)PyArray_NewFromDescr(&PyArray_Type,
257 typecode,
258 0, NULL,
259 NULL, NULL, 0, NULL);
260 if (r == NULL) {
261 Py_XDECREF(outcode);
262 return NULL;
263 }
264 /* the dtype used by the array may be different to the one requested */
265 typecode = PyArray_DESCR(r);
266 if (PyDataType_FLAGCHK(typecode, NPY_USE_SETITEM)) {
267 if (typecode->f->setitem(scalar, PyArray_DATA(r), r) < 0) {
268 Py_DECREF(r);
269 Py_XDECREF(outcode);
270 return NULL;
271 }
272 }
273 else {
274 char *memptr = scalar_value(scalar, typecode);
275
276 memcpy(PyArray_DATA(r), memptr, PyArray_ITEMSIZE(r));
277 if (PyDataType_FLAGCHK(typecode, NPY_ITEM_HASOBJECT)) {
278 /* Need to INCREF just the PyObject portion */
279 PyArray_Item_INCREF(memptr, typecode);
280 }
281 }
282
283 if (outcode == NULL) {
284 return (PyObject *)r;
285 }
286 if (PyArray_EquivTypes(outcode, typecode)) {
287 if (!PyTypeNum_ISEXTENDED(typecode->type_num)
288 || (outcode->elsize == typecode->elsize)) {
289 /*
290 * Since the type is equivalent, and we haven't handed the array
291 * to anyone yet, let's fix the dtype to be what was requested,
292 * even if it is equivalent to what was passed in.
293 */

Callers 3

PyArray_FromAny_intFunction · 0.85
PyArray_EnsureArrayFunction · 0.85

Calls 10

PyArray_DescrFromScalarFunction · 0.85
PyArray_NewFromDescrFunction · 0.85
PyArray_DESCRFunction · 0.85
PyArray_DATAFunction · 0.85
scalar_valueFunction · 0.85
PyArray_ITEMSIZEFunction · 0.85
PyArray_Item_INCREFFunction · 0.85
PyArray_EquivTypesFunction · 0.85
PyArray_CastToTypeFunction · 0.85

Tested by

no test coverage detected