Question about migrating from extract
to extract_bound
#4679
-
I have a rust struct that contains a view of a ndarray with float type (that I'm going to manipulate in rust later): use ndarray::{ArrayViewMut2, Axis, Ix2};
use numpy::{PyArray, PyArrayMethods};
use pyo3::{types::PyAnyMethods, FromPyObject, PyAny, PyResult};
pub struct Float64Block<'a> {
data: ArrayViewMut2<'a, f64>,
} My existing code of implementing impl<'a> FromPyObject<'a> for Float64Block<'a> {
fn extract(ob: &'a PyAny) -> PyResult<Self> {
let array = ob.downcast::<PyArray<f64, Ix2>>()?;
let data = unsafe { array.as_array_mut() };
Ok(Float64Block { data })
}
} The above code works fine. But I would encounter this lifetime issue when I migrate this code to impl<'a> FromPyObject<'a> for Float64Block<'a> {
fn extract_bound(ob: &pyo3::Bound<'a, PyAny>) -> PyResult<Self> {
let array: &pyo3::Bound<'a, PyArray<f64, Ix2>> = ob.downcast()?;
let data: ArrayViewMut2<'a, f64> = unsafe { array.as_array_mut() };
let rs: Float64Block<'a> = Float64Block { data };
Ok(rs)
}
} would result in the following compiler error:
Since I cannot change the function's signature like to |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
I think the solution here is you should use the https://docs.rs/pyo3/latest/pyo3/conversion/trait.FromPyObjectBound.html We are intending to merge those adjustments into |
Beta Was this translation helpful? Give feedback.
You should probably just make a function to do this. This also has the advantage that you can mark it unsafe, which you can't with
FromPyObject
.