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

Function PyArray_CopyObject

numpy/core/src/multiarray/arrayobject.c:237–318  ·  view source on GitHub ↗

* Assign an arbitrary object a NumPy array. This is largely basically * identical to PyArray_FromAny, but assigns directly to the output array. * * @param dest Array to be written to * @param src_object Object to be assigned, array-coercion rules apply. * @return 0 on success -1 on failures. */ NUMPY_API*/

Source from the content-addressed store, hash-verified

235 */
236/*NUMPY_API*/
237NPY_NO_EXPORT int
238PyArray_CopyObject(PyArrayObject *dest, PyObject *src_object)
239{
240 int ret = 0;
241 PyArrayObject *view;
242 PyArray_Descr *dtype = NULL;
243 int ndim;
244 npy_intp dims[NPY_MAXDIMS];
245 coercion_cache_obj *cache = NULL;
246
247 /*
248 * We have to set the maximum number of dimensions here to support
249 * sequences within object arrays.
250 */
251 ndim = PyArray_DiscoverDTypeAndShape(src_object,
252 PyArray_NDIM(dest), dims, &cache,
253 NPY_DTYPE(PyArray_DESCR(dest)), PyArray_DESCR(dest), &dtype, 0);
254 if (ndim < 0) {
255 return -1;
256 }
257
258 if (cache != NULL && !(cache->sequence)) {
259 /* The input is an array or array object, so assign directly */
260 assert(cache->converted_obj == src_object);
261 view = (PyArrayObject *)cache->arr_or_sequence;
262 Py_DECREF(dtype);
263 ret = PyArray_AssignArray(dest, view, NULL, NPY_UNSAFE_CASTING);
264 npy_free_coercion_cache(cache);
265 return ret;
266 }
267
268 /*
269 * We may need to broadcast, due to shape mismatches, in this case
270 * create a temporary array first, and assign that after filling
271 * it from the sequences/scalar.
272 */
273 if (ndim != PyArray_NDIM(dest) ||
274 !PyArray_CompareLists(PyArray_DIMS(dest), dims, ndim)) {
275 /*
276 * Broadcasting may be necessary, so assign to a view first.
277 * This branch could lead to a shape mismatch error later.
278 */
279 assert (ndim <= PyArray_NDIM(dest)); /* would error during discovery */
280 view = (PyArrayObject *) PyArray_NewFromDescr(
281 &PyArray_Type, dtype, ndim, dims, NULL, NULL,
282 PyArray_FLAGS(dest) & NPY_ARRAY_F_CONTIGUOUS, NULL);
283 if (view == NULL) {
284 npy_free_coercion_cache(cache);
285 return -1;
286 }
287 }
288 else {
289 Py_DECREF(dtype);
290 view = dest;
291 }
292
293 /* Assign the values to `view` (whichever array that is) */
294 if (cache == NULL) {

Callers 4

PyArray_SetFieldFunction · 0.85
npyiter_seq_ass_itemFunction · 0.85
array_assign_itemFunction · 0.85
array_assign_subscriptFunction · 0.85

Calls 12

PyArray_NDIMFunction · 0.85
PyArray_DESCRFunction · 0.85
PyArray_AssignArrayFunction · 0.85
npy_free_coercion_cacheFunction · 0.85
PyArray_CompareListsFunction · 0.85
PyArray_DIMSFunction · 0.85
PyArray_NewFromDescrFunction · 0.85
PyArray_FLAGSFunction · 0.85
PyArray_PackFunction · 0.85
PyArray_DATAFunction · 0.85
PyArray_AssignFromCacheFunction · 0.85

Tested by

no test coverage detected