【问题标题】:How do I iterate over a pyo3 PyObject in Rust?如何在 Rust 中迭代 pyo3 PyObject?
【发布时间】:2022-11-09 21:11:25
【问题描述】:

我有一个预先导入的模块,我正在使用 python gil 调用一个方法,如下所示。

Python::with_gil(|py| {
    let res = module.call_method1(py, "my_method", (arg1, arg2))?;
})

这将返回 rust 对象 PyObject,但返回的是 python list。我想遍历这个列表以将内部转换成我可以在 Rust 中使用的东西(它是一个 Numpy 数组的 Python 列表,我正在使用 numpy/ndarray 板条箱)。

我对如何迭代这个有点困惑。如果我尝试将cast_as 换成PyList,我会收到警告:UnsafeCell<PyObject> cannot be shared between threads safely。似乎extract 也不起作用。

如何迭代这个 PyObject?谢谢。

编辑:根据要求添加更多详细信息

如果您使用的是 python 打字系统,python 的返回值是 List[numpy.ndarray]。由于每个 numpy 数组的长度可能不同,我不能将其全部转换为 python 中的 numpy 数组并通过它。示例输出如下:

[array([214.17725372, 192.78236675, 354.27965546, 389.84558392,
          0.99999297])]

我在 Rust 中尝试过的内容:

  • let pylist = res.cast_as::<PyList>(py)?;

    编译失败:UnsafeCell<PyObject> cannot be shared between threads safely

  • let pylist = res.extract::<PyList>(py)?;

    编译失败:the trait 'PyClass' is not implemented for 'PyList'。请注意我在顶部有use pyo3::prelude::*;

  • let pyany = res.extract::<Vec<PyArray1<f64>>>(py)?;

    编译失败:the trait bound 'Vec<PyArray<f64, Dim<[usize; 1]>>>: pyo3::FromPyObject<'_>' is not satisfied。这个 PyArray 来自 numpy 板条箱。

【问题讨论】:

  • 请分享您尝试过的代码。请包含一个包含您的 python 代码的最小示例。
  • 更新了更多细节。 @PitaJ

标签: rust pyo3


【解决方案1】:

我看到您返回了带有dtype=floatnumpy 数组列表。如果您愿意使用另一个依赖项,rust-numpy 可以让您将 numpy 数组映射到 Rust 中的 ndarrays

ndarrays 有一个 .to_vec() 方法来转换成标准的 Rust 容器。

在您的情况下,您可以执行以下操作(未经测试):

use numpy::PyArray1;
use pyo3::{types::IntoPyDict, PyResult, Python};

Python::with_gil(|py| {
    let res: Vec<&PyArray1<f32>> = module // <-- Notice the return type
              .call_method1(py, "my_method", (arg1, arg2))?
              .extract()?; // <--  Notice the extract
})

然后您可以使用res 进行进一步的计算。

println!("I just got a numpy array from python {:?}", res[0]);
println!("I converted that to a vector here: {:?}", res[0].to_vec());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 2022-12-04
    • 2023-04-08
    • 2021-11-19
    • 1970-01-01
    相关资源
    最近更新 更多