Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for arrays of user-defined data-types #138

Closed
g-bauer opened this issue Jul 9, 2020 · 3 comments · Fixed by #218
Closed

Support for arrays of user-defined data-types #138

g-bauer opened this issue Jul 9, 2020 · 3 comments · Fixed by #218

Comments

@g-bauer
Copy link
Contributor

g-bauer commented Jul 9, 2020

AFAIK it is currently not possible to have a PyArrayDyn::<MyClass> where MyClass is a pyclass.
What steps would be necessary to allow for arrays of user-defined data-types?

@kngwyu
Copy link
Member

kngwyu commented Jul 9, 2020

We need some tricks to work it since trait implementation conflicts but I'm sure we can implement that.

@adamreichold
Copy link
Member

adamreichold commented Nov 6, 2021

I think a repr(transparent) wrapper can be used to work around being unable to do

unsafe impl Element for Py<SomeStruct> { ... }

in a downstream crate.

Meaning that

use numpy::{ndarray::Array2, Element, ToPyArray};
use pyo3::prelude::*;

#[pyclass]
#[derive(Debug, Clone)]
pub struct SomeStruct {
    #[pyo3(get)]
    pub bob: bool,
    #[pyo3(get)]
    pub ralph: u16,
}

#[repr(transparent)]
#[derive(Clone)]
pub struct SomeWrapper(pub Py<SomeStruct>);

unsafe impl Element for SomeWrapper {
    const DATA_TYPE: numpy::DataType = numpy::DataType::Object;

    fn is_same_type(dtype: &numpy::PyArrayDescr) -> bool {
        dtype.get_datatype() == Some(numpy::DataType::Object)
    }
}

#[pyfunction]
pub fn gen_some() -> PyObject {
    pyo3::Python::with_gil(|py| {
        let bob = Array2::<SomeWrapper>::from_shape_fn((3, 4), |(n, m)| {
            SomeWrapper(
                Py::new(
                    py,
                    SomeStruct {
                        bob: (n * m) % 2 == 0,
                        ralph: ((n * m) % 65536) as u16,
                    },
                )
                .unwrap(),
            )
        });

        bob.to_pyarray(py).to_object(py)
    })
}

#[pymodule]
fn pyobj(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<SomeStruct>()?;
    m.add_function(wrap_pyfunction!(gen_some, m)?)?;
    Ok(())
}

seems to work even though it is a bit unergonomic on the Rust side. At least it does not seem to immediately crash on the Python side

import pyobj

a = pyobj.gen_some()

print(a[1,3].ralph)

@adamreichold
Copy link
Member

If PyArray<PyObject>, I wonder if we should add the above as an example to the repository?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants