MCPcopy Create free account
hub / github.com/PyO3/rust-numpy / extract

Method extract

src/array_like.rs:143–190  ·  view source on GitHub ↗
(ob: Borrowed<'a, 'py, PyAny>)

Source from the content-addressed store, hash-verified

141 type Error = PyErr;
142
143 fn extract(ob: Borrowed<'a, 'py, PyAny>) -> PyResult<Self> {
144 if let Ok(array) = ob.cast::<PyArray<T, D>>() {
145 return Ok(Self(array.readonly(), PhantomData));
146 }
147
148 let py = ob.py();
149
150 // If the input is already an ndarray and `TypeMustMatch` is used then no type conversion
151 // should be performed.
152 if (C::ALLOW_TYPE_CHANGE || ob.cast::<PyUntypedArray>().is_err())
153 && matches!(D::NDIM, None | Some(1))
154 {
155 if let Ok(vec) = ob.extract::<Vec<T>>() {
156 let array = Array1::from(vec)
157 .into_dimensionality()
158 .expect("D being compatible to Ix1")
159 .into_pyarray(py)
160 .readonly();
161 return Ok(Self(array, PhantomData));
162 }
163 }
164
165 let (dtype, flags) = if C::ALLOW_TYPE_CHANGE {
166 (Some(T::get_dtype(py)), NPY_ARRAY_FORCECAST)
167 } else {
168 (None, 0)
169 };
170
171 let newtype = dtype
172 .map(|dt| dt.into_ptr().cast())
173 .unwrap_or_else(std::ptr::null_mut);
174
175 let array = unsafe {
176 let ptr = PY_ARRAY_API.PyArray_FromAny(
177 py,
178 ob.as_ptr(),
179 newtype,
180 0,
181 0,
182 flags,
183 std::ptr::null_mut(),
184 );
185
186 pyo3::Bound::from_owned_ptr_or_err(py, ptr)?
187 };
188
189 Ok(Self(array.extract()?, PhantomData))
190 }
191}
192
193/// Receiver for zero-dimensional arrays or array-like types.

Callers

nothing calls this directly

Calls 3

readonlyMethod · 0.80
into_pyarrayMethod · 0.80
castMethod · 0.80

Tested by

no test coverage detected