2

I have a rust struct that uses the pyo3 pyclass macro to allow using in python. This works fine for simple structs but if I have a struct that contains a type from a different library it becomes more difficult.

Example:

use geo::Point;

#[pyclass]
#[derive(Clone, Copy)]
pub struct CellState {
    pub id: u32,
    pub position: Point<f64>,
    pub population: u32,
}

Above we use the Point type from the rust geo library. The compiler provides the following error: the trait `pyo3::PyClass` is not implemented for `geo::Point<f64>

If I then try to implement PyClass on the Point:

impl PyClass for Point<f64> {}

It gives me the following compiler error: impl doesn't use only types from inside the current crate

Any ideas on a clean and simple way to resolve this?

sam
  • 1,005
  • 1
  • 11
  • 24

1 Answers1

0

Until a better answer comes up my solution was to nest the class inside a python class but I then had to manually write the getters and setters.

#[pyclass]
#[derive(Clone)]
pub struct CellStatePy {
    pub inner: CellState,
}

#[pymethods]
impl CellStatePy {
    #[new]
    pub fn new(id: u32, pos: (f64, f64), population: u32) -> Self {
        CellStatePy {
            inner: CellState {
                id: CellIndex(id),
                position: point!(x: pos.0, y: pos.1),
                population,
            },
        }
    }
}

Then implement PyObjectProtocol:

#[pyproto]
impl PyObjectProtocol for CellStatePy {
    fn __str__(&self) -> PyResult<&'static str> {
        Ok("CellStatePy")
    }

    fn __repr__<'a>(&'a self) -> PyResult<String> {
        Ok(format!("CellStateObj id: {:?}", self.inner.id))
    }

    fn __getattr__(&'a self, name: &str) -> PyResult<String> {
        let out: String = match name {
            "id" => self.inner.id.into(),
            "position" => format!("{},{}", self.inner.position.x(), self.inner.position.y()),
            "population" => format!("{}", self.inner.population),
            &_ => "INVALID FIELD".to_owned(),
        };
        Ok(out)
    }
}

sam
  • 1,005
  • 1
  • 11
  • 24