python - 在包含来自不同 crate 的类型的使用rust 结构上使用pyo3 pyclass

标签 python rust pyo3

我有一个使用pyo3 pyclass宏的rust结构,以允许在python中使用。这对于简单的结构很好用,但是如果我的结构包含来自不同库的类型,则将变得更加困难。
例子:

use geo::Point;

#[pyclass]
#[derive(Clone, Copy)]
pub struct CellState {
    pub id: u32,
    pub position: Point<f64>,
    pub population: u32,
}
在上面,我们使用rust地理库中的Point类型。编译器提供以下错误:the trait `pyo3::PyClass` is not implemented for `geo::Point<f64>如果然后尝试在Point上实现PyClass:
impl PyClass for Point<f64> {}
它给了我下面的编译器错误:impl doesn't use only types from inside the current crate有任何干净,简单的方法解决此问题的想法吗?

最佳答案

在找到更好的答案之前,我的解决方案是将类嵌套在python类中,但随后我不得不手动编写getter和setter。

#[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,
            },
        }
    }
}
然后实现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)
    }
}

关于python - 在包含来自不同 crate 的类型的使用rust 结构上使用pyo3 pyclass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393247/

相关文章:

rust - 这种借用 "Rust way"吗?

python - 如何在Rust中将PyArray转换为Vec <Vec <T >>

python - XML 走在 python 中

python - 使用 scipy/simplex 进行线性优化不能提供最佳效果

python - 如何使用 Gio 设置 HTTP 请求的用户代理?

python - matplotlib 导入时需要时间

使用 Drop trait 释放 repr(C) 结构的正确习惯用法

enums - 特征绑定(bind) io::Error: Clone is not satisfied when implementing a custom error enum

python - 使用 PyO3 和 Maturin 交叉编译(unixlike 到 windows)

python - 为什么 cython embed 插件在 python 解释器中的性能比 rust-c 接口(interface)版本更高?