* 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*/
| 235 | */ |
| 236 | /*NUMPY_API*/ |
| 237 | NPY_NO_EXPORT int |
| 238 | PyArray_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) { |
no test coverage detected