Accessing PyArray within Py<> wrapper in PyO3

I'm writing Python bindings with PyO3 for a Python module.

In a Rust lib crate, I have a method whose signature is:

fn fit(&mut self, X: ArrayView2<T>, y: ArrayView1<T>) -> Array1<T>;

In my PyO3 interface code, I expose a method fit which takes two instances of PyArray as arguments:

#[pymethods]
impl Lasso {
    fn fit<'py>(
        &mut self,
        py: Python<'py>,
        X: Py<PyArray2<f32>>,
        y: Py<PyArray1<f32>>,
    ) -> PyResult<&'py PyArray1<f32>> {
        Ok(PyArray::from_array(
            py,
            &self.inner.fit(X.as_array(), y.as_array()),
        ))
    }
}

I don't know how to access the PyArray2 object from the Py<> wrapper of X (same issue for y). The method inner.fit(X, y) expects two instances of ArrayView which I can get from PyArray objects using the as_array() method. But I struggle at converting my X and y objects from Py<PyArray2<f32>> to PyArray2<f32>.

Any help would be very much appreciated.

Problem solved.

Solution found:

Instead of passing as arguments Py<PyArray2<f32>>, pass &PyArray2<f32>. It does not raise any issues and allows you to directly access the ArrayView using as_array().

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.