【问题标题】:PyO3 implement python iterable class in RustPyO3 在 Rust 中实现 python 可迭代类
【发布时间】:2021-06-22 05:10:58
【问题描述】:

我已经 found example 了解如何在 Rust 中实现 PyIterProtocol。

use pyo3::prelude::*;
use pyo3::PyIterProtocol;
use pyo3::class::iter::IterNextOutput;

#[pyclass]
struct Iter {
    count: usize
}

#[pyproto]
impl PyIterProtocol for Iter {
    fn __next__(mut slf: PyRefMut<Self>) -> IterNextOutput<usize, &'static str> {
        if slf.count < 5 {
            slf.count += 1;
            IterNextOutput::Yield(slf.count)
        } else {
            IterNextOutput::Return("Ended")
        }
    }
}

但我不知道如何实现一个可迭代但本身不是迭代器的容器类。本质上,我希望能够在 Python 中分解我的对象,例如

x, y, z = my_object

【问题讨论】:

    标签: python rust cpython pyo3


    【解决方案1】:

    来自the user guide on Iterator Types:

    在许多情况下,您会区分被迭代的类型(即 iterable)和它提供的迭代器。在这种情况下,您应该为 iterable 和 iterator 实现 PyIterProtocol,但 iterable 只需要支持 __iter__() 而 iterator 必须同时支持 __iter__() 和 __next__()。

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2021-08-02
      • 2020-03-31
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      相关资源
      最近更新 更多