rust PyO3 Trait Clone未为“PyList”实现

wlwcrazw  于 2023-11-19  发布在  其他
关注(0)|答案(1)|浏览(136)

我正在尝试使用PyO 3绑定在Rust中创建自己的Python库。虽然它给了我这个奇怪的错误,但我似乎无法修复。我试图将其转移到引用到PyList,但它只需要我指定一个生存期;然后反过来需要我使用PyO 3不允许的泛型。
下面是错误和我的代码:

error[E0277]: the trait bound `PyList: Clone` is not satisfied
 --> src\lib.rs:8:5
  |
5 | #[derive(Clone)]
  |          ----- in this derive macro expansion
...
8 |     arguments: PyList,
  |     ^^^^^^^^^^^^^^^^^ the trait `Clone` is not implemented for `PyList`
  |
  = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info)

个字符

pw9qyyiw

pw9qyyiw1#

您可能不想直接存储PyList,而是Py<PyList>。这将允许您避免#[pyclass(unsendable)],同时也是Clone

use pyo3::types::PyList;
use pyo3::prelude::*;

#[pyclass]
#[derive(Clone)]
struct Crust {
    #[pyo3(get, set)]
    arguments: Py<PyList>,
}

#[pymethods]
impl Crust {
    #[new]
    fn new(arguments: Py<PyList>) -> Self {
        Crust { arguments }
    }

    fn add_argument(&self, name: String, callback: PyObject) -> PyResult<()> {
        Python::with_gil(|py| {
            print!("Current arguments: {:?}", self.arguments);
        });
        Ok(())
    }
}

#[pymodule]
fn crust(_py: Python, m: &PyModule) -> PyResult<()> {
    m.add_class::<Crust>()?;
    Ok(())
}

字符串

相关问题