未为“PyList”实现 PyO3 特征克隆

PyO3 Trait Clone is not implemented for 'PyList'

提问人:Brody Critchlow 提问时间:11/3/2023 更新时间:11/3/2023 访问量:44

问:

我正在尝试使用 PyO3 绑定在 Rust 中制作自己的 Python 库。虽然它给了我这个奇怪的错误,但我似乎无法修复。我试图将它移至 PyList 的引用,但它只需要我指定一个生命周期;这反过来又需要我使用 PyO3 不允许的泛型。

这是错误,以及我的代码:

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)
use pyo3::types::PyList;
use pyo3::prelude::*;

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

#[pymethods]
impl Crust {
    #[new]
    fn new(arguments: 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(())
}
PYO3型

评论


答:

3赞 Chayim Friedman 11/3/2023 #1

您可能不想直接存储,而是 Py<PyList>。这将使你能够避免 并且也是 .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(())
}